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?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
For
intthere’s no difference. Theint a = 1;syntax is copy-initialziation, whileint 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 declaredexplicit.To spell this out, direct-initialization directly calls the corresponding constructor:
On the other hand, copy-initialization behaves “as if” a copy is made:
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: