c++ - unique_ptr 无法初始化

标签 c++ initialization unique-ptr member-initialization

<分区>

我在项目中有以下代码,它给我一个错误 C2059,unique_ptr 行错误的语法错误"new"。

#include <memory>

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

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

这里发生了什么?

最佳答案

您正在尝试使用 default member initializer , 但以错误的方式。它必须只是一个大括号初始化器(或等于初始化器)(包含在成员声明中)。

你可以使用 list initialization (自 C++11 起):

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

member initialization list :

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

关于c++ - unique_ptr 无法初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39097027/

相关文章:

c++ - 使用 QSound (Qt) 播放 .wav 没有声音

java - Java中的双数组初始化

java - 静态变量初始化java

c++ - 调用带有 unique_ptr 对象的函数

c++ - 获取智能指针的指针指针

c++ - 嵌入式 Python 段错误

c++ - 使用 Boost 图的大小变化图

c# - 托管和非托管代码错误 C3699

c - 如何在C编程中初始化多维数组

c++ - 使用 make_unique 语句重新分配 unique_ptr 对象 - 内存泄漏?