struct A
{
int a;
std::string str;
};
A a;// 1
A a{};// 2
A a = {};// 3
A a = A();// 4
There seems to be all options. In case 1 and 4 a
will be uninitialized, in 2 and 3 a
will be initialized with zero and they both are same and just the matter of style or there is some difference? 4 supposed to first create a temporary object and then assign it to an a
, but it will happen only if I will turn off comliler's optimization completely, right?
For all the cases the data member str
is always default-initialized by the default constructor of std::string
. Due to the different initialization styles, the data member a
might be initialized to 0
or indeterminate value. In details,
The 1st one is default initialization , as the result aa
is initialized to indeterminate value (or gets zero-initialized to 0
if a
is static or thread-local object), a.str
is initialized by its default constructor.
The 2nd one is direct-list-initialization and aggregate initialization is performed, as the result aa
isvalue-initialized ( zero-initialized ) to 0
, a.str
is initialized by its default constructor.
The 3rd one is copy-list-initialization and aggregate initialization is performed, as the result aa
is value-initialized (zero-initialized) to 0
, a.str
is initialized by its default constructor.
In concept the 4th one is copy initialization , a
is copy-initialized from A()
(value-initialized temporary A
). Because of copy elision (since C++17 it's mandatory) a
might be value-initialized directly, as the result (which doesn't get changed by copy elision) aa
is zero-initialized to 0
, a.str
is initialized by its default constructor.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.