Reputation: 12116
I've seen various conflicting references to the copy constructor behaviour of STL strings in C++ and I was hoping someone could clarify this for me, given the following code segment:
string str() { return string("this is a string"); }
//meanwhile, in some other function...
string s = str();
Does the object 's' constitute a deep copy of the string object defined in the function 'str()'? or is the object 's' simply pointing at the same chunk of memory allocated during the string constructor call in the 'str()' function?
Upvotes: 13
Views: 23887
Reputation: 272467
Yes, it performs a logical deep copy.
From N3126, 21.4.2, Table 61:
data()
- points at the first element of an allocated copy of the array whose first element is pointed at bystr.data()
Upvotes: 1
Reputation: 16148
String will deep copy, they do not shared the same buffer.
That said when returning them from a function most good compilers can either use Return Value Optimisation or Copy elision so that manoeuvre isn't all that expensive (or even free).
If you are using c++11 then move semantics are specified by the standard so for thing like return string rest assured that the worst case (even without optimisations) is fairly cheap.
EDIT: to summarise, you are guaranteed that the string you "own" will have a unique chunk of memory which will persist for at least the life time of the local string. However it is more than likely that the compiler won't copy it from the string in the function but rather just swap it's pointers or even elided the copy altogether (meaning the string in the function would actually be the string you assign too).
Upvotes: 9