What's being used is called Uniform Initialization.
Looks a bit odd, I admit. The function knows it needs to return a string
, but it's been fed a pair of iterators. The curly braces allow the compiler to attempt to construct a string
based on the contents of the braces, and sure enough, constructor number six listed here will attempt to construct a string from a begin and end iterator.
So
return {str.rbegin(), str.rend()};
is in more familiar syntax
return string(str.rbegin(), str.rend());
The next bit of magic is rbegin
and rend
provide reverse iterators, so the input string
will be read backward into the output string
.
string
iterators are Random Access Iterators, so the iterator will be traversed in O(N) time. There isn't that much magic in building the new string, copying the old string and maybe some buffer resizing, the new string will be built in O(N) time PLUS any time required to size the buffer backing the new string
.
This results in either
- O(N) complexity because the buffer is presized before copying copying N elements from one
string
to the other, or
- Amortized O(N) complexity because the buffer is resized on demand, resulting in some additional allocating and copying of old buffer to new as well as copying from one
string
to the other.
The second option is possible because the string
constructor does not require the input iterator to be random access, making computing the size of the required buffer for presizing potentially more expensive than resizing. But it might have a special case testing for random access and presizing.