Reputation: 5824
If s1
and s2
are strings, then (as far as I can tell)
s1 = s2.substr();
means exactly the same as
s1 = s2;
Why would somebody want to call substr()
without any arguments?
Edit: Another way to phrase the same question:
Why does the standard define substr
thus:
basic_string substr( size_type pos = 0,
size_type count = npos ) const;
rather than thus:
basic_string substr( size_type pos,
size_type count = npos ) const;
Upvotes: 4
Views: 378
Reputation: 42588
In some cases, the logic might flow better with substr()
.
Imagine a case where you have a buffer as a string pointer and a pointer to some string metrics object.
if (metrics) {
substring = buffer->substr(metrics->pos(), metrics->len());
} else {
substring = buffer->substr();
}
reads better than
if (metrics) {
substring = buffer->substr(metrics->pos(), metrics->len());
} else {
substring = *buffer;
}
Upvotes: 2
Reputation: 45654
The answer is, just for the heck of it.
As you rightly noticed, it has no advantage (and sometimes a speed disadvantage) to just creating a copy.
Speculating why the first argument is defaulted at all, I guess that it was meant as a way to force un-sharing of ancient COW strings (not allowed by current standards). Or someone was over-zealous when adding default arguments. It happens to the best of us.
Upvotes: 5