c++ - 析构函数和 unique_ptr

标签 c++ c++11 unique-ptr

我有以下代码

class A {
    public:
        A(){}
        ~A(){}
    private:
        std::vector<std::unique_ptr<double> > x;
};

A f() {
    A a;
    return a;
}

int main() {
    A a=f();
    return 0;
}

除非我注释掉析构函数,否则它不会编译(gcc 4.7)。实际上,我的代码中并不需要这个析构函数,我只是想将它用于调试目的。

但是,我不明白发生了什么,因此我担心我做错了什么。这里发生了什么?

最佳答案

这是因为显式定义的析构函数的存在阻止了为 A 隐式生成移动构造函数。

根据 C++11 标准的第 12.8/9 段:

If the definition of a class X does not explicitly declare a move constructor, one will be implicitly declared as defaulted if and only if

— X does not have a user-declared copy constructor,

— X does not have a user-declared copy assignment operator,

— X does not have a user-declared move assignment operator,

X does not have a user-declared destructor, and

— the move constructor would not be implicitly defined as deleted.

现在没有移动构造函数,为了从 f() 返回值,编译器将尝试调用隐式生成的复制构造函数(为了向后兼容仍在生成该构造函数)。但是,std::unique_ptr 是不可复制的。因此,错误。

显式定义移动构造函数(或将其声明为默认构造函数,如评论中 juanchopanza 的建议)将解决问题。

关于c++ - 析构函数和 unique_ptr,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15485863/

相关文章:

c++ - std::make_unique<std::thread> 与 lambda

python - 尝试使用 swig 将 c++ 库包装到 Python 时,体系结构 x86_64 的 undefined symbol

c++ - boost::thread 和 std::thread 兼容性问题?

multithreading - 使用 std::atomic 在 C++11 中编写线程安全的双端队列

c++ - 具有智能指针的非虚拟删除器

C++ unique_ptr 和数组

c++ - 迷你过滤器无法阻止 'Windows Photos' 打开的图像

c++ - ListView 控件忽略扩展样式

c++ - FreeRTOS CPP 函数指针

C++:包含它所属的类的 union