Copy initialization and Direct Initialization

what i understood is that the compiler will make a temp string object with the value "Test" and then copy it to a and , in the case of b the compiler will use the constructor without creating temporary objects.

1
2
string a = "Test";
string b("Test");


is there a loss of performance when using Copy initialization form
or i understood wrong ?

> string a = "Test"; // copy initialisation
> string b("Test"); // direct initialisation
> is there a loss of performance when using Copy initialization

No (C++17).
Typically, no (C++14).

When a nameless temporary, not bound to any references, would be moved or copied into an object of the same type (ignoring top-level cv-qualification), the copy/move is omitted. When that temporary is constructed, it is constructed directly in the storage where it would otherwise be moved or copied to.
See copy elision: http://en.cppreference.com/w/cpp/language/copy_elision

This optimisation is: mandatory in C++17; permitted (supported by all mainstream compilers) pre-C++17

Direct initialisation is usually preferred; copy initialisation is less flexible.
See 'Notes' in http://en.cppreference.com/w/cpp/language/copy_initialization
Last edited on
Thanks JLBorges for replying and helping me.
I understood it clearly now.
Topic archived. No new replies allowed.