0

What is difference between initializing x1 and x2?

struct X {
    int i;
};

void func(){
    X x1 = {2};
    X x2 {2};

    cout << x1.i << ", " << x2.i << endl;
}
nullptr
  • 3,320
  • 7
  • 35
  • 68
  • http://stackoverflow.com/questions/1051379/is-there-a-difference-in-c-between-copy-initialization-and-direct-initializati – 101010 Apr 03 '17 at 08:56
  • Possible duplicate of [Is there a difference in C++ between copy initialization and direct initialization?](http://stackoverflow.com/questions/1051379/is-there-a-difference-in-c-between-copy-initialization-and-direct-initializati) – Manoj Apr 03 '17 at 09:02
  • @101010 it doesnt seem relataed. – nullptr Apr 03 '17 at 09:09
  • @Manoj in that question, () operators used. I have used {} operator. – nullptr Apr 03 '17 at 09:09
  • oops sorry..... – Manoj Apr 03 '17 at 09:17

1 Answers1

2
X x1 = {2};

Is copy-list-initialization.

X x2 {2};

Is direct-initialization.


Both syntaxes perform aggregate initialization, because X is an aggregate.


What is difference

Braces can not be elided with the direct-initialization form (until C++14).

In general, copy initialization only considers non-explicit constructors and conversion functions and direct initialization considers also explicit ones. However, this does not apply to aggregate initialization.


with and without = operator

The equals (=) character here isn't actually an operator. It is part of the syntax of copy initialization.

eerorika
  • 232,697
  • 12
  • 197
  • 326
  • @UDPLover there is no performance difference between aggregate initialization and aggregate initialization. – eerorika Apr 03 '17 at 10:31