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?
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
};
Both end up being the same when all is 1s and 0s, just be consistent.
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