Search code examples
c++initializationlanguage-lawyerlist-initializationcopy-elision

How does this list-like initialization work?


I know about several types of initialization in C++ and recently learned why list initialization should be preferred. But what about this code? live demo

#include <iostream>
#include <string>

class A {
public:
    A(int x, std::string y) { std::cout << "normal\n"; }

    A(const A& obj) { std::cout << "copy\n"; }
};

int main(){
    A a({1, "2"}); // strange initialization
}

Prints:

normal

It looks like some kind of list initialization mixed with a construtor call using parentheses. So I thought it would create a temporary instance of A from {1, "2"} and then call the copy-constructor. But that doesn't happen. Instead it behaves like list-initialization. Maybe I'm just confused by the syntax and it is list-initialization?

If it is, how does the syntax work here? If not, what kind of initialization is this?


Solution

  • So I thought it would create a temporary instance of A from {1, "2"} and then call the copy-constructor.

    You're right. Here the object a is initialized via the constructor A::A(int x, std::string y) directly because of copy elision.

    You can compile with -fno-elide-constructors option (with pre-C++17 mode, since C++17 this kind of copy elision is guaranteed), you'll get

    normal
    copy
    

    LIVE