简体   繁体   中英

C++ STL String Copy Constructor - Always a Deep Copy?

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?

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).

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 by str.data()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM