There is no difference for int
. Syntax int a = 1;
- this is copy-initialization, and int a(1);
- direct initialization. The compiler is almost guaranteed to generate the same code even for generic class types, but copy initialization requires that the class does not have a copy constructor declared explicit
.
To record this, direct initialization directly calls the appropriate constructor:
T x(arg);
On the other hand, copy initialization behaves like a “copy”:
T x = arg;
Copy-permission is explicitly allowed and encouraged, but the “as if” construct must still be valid, i.e. the copy constructor should be accessible, not explicitly or deleted. 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 };
source share