简体   繁体   English

直接初始化与值初始化

[英]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. 我是一名试图学习C ++ 11的C程序员,但遇到了一些我不了解的东西。 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: 以下代码段无法使用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 错误C2797:“ TestClass :: _ msg”:成员初始化程序列表或非静态数据成员初始化程序内部的列表初始化未实现

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. 这是Visual C ++编译器的实现细节。 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 Visual Studio中的C ++编译器未在成员初始值设定项列表或非静态数据成员初始值设定项内实现列表初始化

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. 它将按您的预期工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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