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 ?
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With