简体   繁体   中英

Direct Initialization vs. Value Initialization

I am a C programmer trying to learn C++11, and I've run into something I don't understand. From what I can tell, the following issue is a difference between value initialization and direct initialization.

The following code snippet does not compile using Visual Studio:

class TestClass {
    int _val;
    std::string _msg;
public:
    TestClass(int, std::string);
    void action();
};

TestClass::TestClass(int val, std::string msg)
    : _val{val}, _msg{msg}
{
}

void TestClass::action()
{
    std::cout << _msg << _val << std::endl;
}

It gives me:

error C2797: 'TestClass::_msg': list initialization inside member initializer list or non-static data member initializer is not implemented

However, changing

TestClass::TestClass(int val, std::string msg)
    : _val{val}, _msg{msg}

to

TestClass::TestClass(int val, std::string msg)
    : _val{val}, _msg(msg)

fixes my problem. What is the difference between these two forms of initialization, and when should one be used over the other? I've been led to believe that I should use value initialization whenever dealing with explicit types.

This is an implementation detail of the Visual C++ compiler. You can read more about this error here . The page states:

The C++ compiler in Visual Studio does not implement list initialization inside either a member initializer list or a non-static data member initializer

Your code attempts to implement the first case. The solution you proposed solves this problem, but if you still prefer to use the initializer list somehow in the constructor, you can do this:

TestClass::TestClass(int val, std::string msg)
    : _val{val}, _msg(std::string{msg})

Which will work as you intend.

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