0

我在一个项目中有以下代码,它给了我一个错误 C2059,语法错误“新”,该unique_ptr行是错误的。

#include <memory>

class Nothing {
public:
    Nothing() { };
};
class IWriter
{
    public:
        IWriter() {
        }

        ~IWriter() {
        }
    private:
        std::unique_ptr<Nothing> test(new Nothing());
};

这里发生了什么?

4

1 回答 1

4

您正在尝试使用默认成员初始化程序,但方式错误。它必须只是一个大括号初始值设定项(或等于初始值设定项)(包含在成员声明中)。

您可以使用列表初始化(C++11 起):

std::unique_ptr<Nothing> test{ new Nothing() };

成员初始化列表

class IWriter
{
    public:
        IWriter() : test(new Nothing) {
        }
        ~IWriter() {
        }
    private:
        std::unique_ptr<Nothing> test;
};
于 2016-08-23T09:15:10.110 回答