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

Possible duplicate:
When should direct initialization be used when copying is initialized?

I know both

int a = 1; 

and

 int a(1); 

works in C ++, but which one is better to use?

+4
source share
3 answers

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; // "as if" T x(T(arg));, but implicitly so 

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 }; 
+11
source

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

+1
source

When you use primitive types, as in your example, it makes no difference. With classes, the assignment form is theoretically less efficient, since it may include an additional call to the copy constructor; in practice, however, I expect this call to be optimized almost always.

On the other hand, the second form may occur in the so-called C ++ most unpleasant parsing , this statement seems to be:

 ab(c()); 

interpreted as a function declaration, not a variable definition.

I find the second problem more alarming than the first, so I consistently use the assignment style of the definition of a variable.

+1
source

Source: https://habr.com/ru/post/1415736/


All Articles