Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why call basic_string::substr with no arguments?

Tags:

c++

stdstring

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;
like image 537
oz1cz Avatar asked Oct 18 '25 13:10

oz1cz


2 Answers

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.

like image 136
Deduplicator Avatar answered Oct 21 '25 01:10

Deduplicator


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;
}
like image 42
Jeffery Thomas Avatar answered Oct 21 '25 01:10

Jeffery Thomas