Is it considered better to use c-like initialization or constructor initialization in C++?

c++, constructor, initialization

Solution

For `int` there's no difference. The `int a = 1;` syntax is copy-initialziation, while `int a(1);` is direct-initialization. The compiler is almost guaranteed to generate the same code even for general class types, but copy-initialization requires that the class not have a copy constructor that is declared `explicit`.

To spell this out, direct-initialization directly calls the corresponding constructor:

T x(arg);

On the other hand, copy-initialization behaves "as if" a copy is made:

T x = arg; // "as if" T x(T(arg));, but implicitly so

Copy-elision is explicitly allowed and encouraged, but the "as if" construction must still be valid, i.e. the copy constructor must be accesible and not explicit or deleted. An example:

struct T
{
    T(int) { } // one-argument constructor needed for `T x = 1;` syntax

    // T(T const &) = delete;            // Error: deleted copy constructor
    // explicit T(T const &) = default;  // Error: explicit copy constructor
    // private: T(T const &) = default;  // Error: inaccessible copy constructor
};

Problem

Possible Duplicate: When should you use direct initialization and when copy initialization? I know that both ``` int a = 1; ``` and ``` int a(1); ``` work in C++, but which one is considered better to use?

Original source

Related problems