Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 295
Gearoid Murphy Avatar asked Dec 11 '11 20:12

Gearoid Murphy


People also ask

Are copy constructors deep copies?

The default copy constructor and default assignment operators do shallow copies, which is fine for classes that contain no dynamically allocated variables. Classes with dynamically allocated variables need to have a copy constructor and assignment operator that do a deep copy.

Does copy constructor create shallow copy?

The default copy constructor in C++ can only create a shallow copy of an object.

Does std :: string constructor copy?

std::string::string. Constructs an empty string, with a length of zero characters. Constructs a copy of str. Copies the portion of str that begins at the character position pos and spans len characters (or until the end of str, if either str is too short or if len is string::npos).

Is copy constructor necessary?

A user-defined copy constructor is generally needed when an object owns pointers or non-shareable references, such as to a file, in which case a destructor and an assignment operator should also be written (see Rule of three).


1 Answers

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

like image 113
111111 Avatar answered Sep 29 '22 03:09

111111