4

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?

Community
  • 1
  • 1
Orcris
  • 3,135
  • 6
  • 24
  • 24

3 Answers3

11

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
};
Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
1

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

Kevin DiTraglia
  • 25,746
  • 19
  • 92
  • 138
1

When you're using primitive types as in your example it doesn't make any difference. With classes the assignment form is theoretically less efficient, as it may involve an additional call to a copy constructor; in practice however I expect this call to be optimized away almost always.

On the other hand the second form may incur in what is known as C++'s most vexing parse, that is a statement like:

a b(c());

is interpreted as a function declaration rather than a variable definition.

I consider the second problem more worrisome than the first, so I consistently use the assignment style of variable definition.

Nicola Musatti
  • 17,834
  • 2
  • 46
  • 55