简体   繁体   中英

Braced initialization in C++03

Is this program supposed to correctly initialize the string, in C++03?

#include <iostream>
#include <string>

struct A
{
    std::string s;
};

int main()
{
    A a = { };
    std::cout << a.s.size() << std::endl;

}

Using bcc32 6.70, the output is 256 , and inspecting the string in the debugger, its internal pointers appear to be garbage addresses.

A is an aggregate and C++03 allows initialization of aggregates using a braced initializer-list. If the initializer-list is empty, then each member of the aggregate is value initialized.

From C++03 [dcl.init.aggr]/8

... An empty initializer-list can be used to initialize any aggregate. If the aggregate is not an empty class, then each member of the aggregate shall be initialized with a value of the form T() (5.2.3), where T represents the type of the uninitialized member.

In your example the std::string member should be default initialized.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM