Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ string initialization

Tags:

c++

I've seen a statement according to which

string noun("ants");
string noun = "ants";

are exactly equivalent.

This is contrary to my intuition: I thought in the second case a conversion occurs (via a constructor of the string class), then the assignment operator gets called with an argument of class string. What is there actually happening ?

like image 754
Radu Stoenescu Avatar asked Dec 20 '22 15:12

Radu Stoenescu


1 Answers

For initialization of a variable definition using assignment, like

std::string a = "foo";

Here two objects are created: The variable you define (a in my example) and a temporary object (for the string "foo"). Then the copy-constructor of your variable (a) is called with the temporary object, and then the temporary object is destructed. The copy-assignment operator is not called.

However, the copying can be avoided if the compiler uses copy elision, which is an optimization technique to avoid unnecessary copies and copying. The copy-constructor needs to be there anyway, even if it's not called.


For the definition

std::string a("foo");

there is a better constructor which takes a pointer to a constant string, which the literal "foo" can be seen as (string literals are actually constant arrays of char, but like all arrays they decay to pointers).

like image 144
Some programmer dude Avatar answered Jan 03 '23 13:01

Some programmer dude