Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 859
Orcris Avatar asked Dec 13 '22 01:12

Orcris


2 Answers

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
};
like image 123
Kerrek SB Avatar answered Dec 14 '22 15:12

Kerrek SB


Both end up being the same when all is 1s and 0s, just be consistent.

like image 21
Kevin DiTraglia Avatar answered Dec 14 '22 14:12

Kevin DiTraglia