简体   繁体   中英

Empty initializer list as argument doesn't call default constructor

The following code

class A {
public:
    A() {} // default constructor
    A(int i) {} // second constructor
};
int main() {
    A obj({});
}

calls the second constructor. Probably the empty initializer_list is treated as one argument and is converted to int . But when you remove the second constructor from the class, it calls the default constructor. Why?

Also, I understand why A obj { {} } will always call a constructor with one argument as there we are passing one argument which is an empty initializer_list .

The presence of the parentheses surrounding the braces in A obj({}); indicates the single argument constructor will be called, if possible. In this case it is possible because an empty initializer list, or braced-init-list , can be used to value initialize an int , so the single argument constructor is called with i=0 .

When you remove the single argument constructor, A obj({}); can no longer call the default constructor. However, the {} can be used to default construct an A and then the copy constructor can be called to initialize obj . You can confirm this by adding A(const A&) = delete; , and the code will fail to compile.

It's because the {} in A obj({}); ends up being interpreted as of type int . So the code ends up being similar to A obj(0); .

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