c++ - 包含 unique_ptr 的结构中的默认析构函数在使用 std::map 时导致编译错误

标签 c++ dictionary destructor unique-ptr

考虑以下代码示例,为什么默认析构函数的定义会导致编译错误?

#include <iostream>
#include <memory>
#include <map>

struct Foo
{
    char c;
    std::unique_ptr<int> ptr;

    Foo(char c_, int n_) : c(c_), ptr(std::make_unique<int>(n_))
    {;}

    //~Foo() noexcept = default; // problem here, why?
};


int main()
{
    std::map<int, Foo> mp;

    mp.emplace(0, Foo{'a',40});
    mp.emplace(1, Foo{'b',23});

    for (auto &&i : mp)
        std::cout<< i.first << " : {" << i.second.c << "," << *(i.second.ptr) << "}" <<std::endl;
}

编译器错误:

error: call to implicitly-deleted copy constructor of 'Foo'

从错误消息中我得知正在发生静默复制???

值得一提的是,当使用普通指针而不是 unique_ptr 时,代码可以正常编译。但是我不明白为什么默认的析构函数会出问题?

最佳答案

因为如果您自己定义析构函数,那么编译器将不再为您生成复制条件和移动条件。您可以将它们指定为默认值并删除(即使由于 unique_ptr 的原因,复制 con 仍将被隐式删除)并且您的代码将再次运行:

struct Foo
{
    char c;
    std::unique_ptr<int> ptr;

    Foo(char c_, int n_) : c(c_), ptr(std::make_unique<int>(n_))
    {;}

    ~Foo() noexcept = default;
    Foo(Foo&&) = default;
};

operator=(Foo&&) 也是如此。

关于c++ - 包含 unique_ptr 的结构中的默认析构函数在使用 std::map 时导致编译错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56821044/

相关文章:

c++ - 返回指向类的指针的函数

c++ - reinterpret_cast - 奇怪的行为

c++ - 跟踪重复键 STL 映射?

c# - 如何检查字典中是否存在键值对

python - 使用 python 替换字典中矩阵键返回错误的选项

c++ - 编译器什么时候为类的特殊成员提供定义?

c++ - 类是否应该具有双重破坏的弹性?

c++ - 为什么 boost::function 慢?

c++ - QObject::connect: 没有这样的信号(类名)(信号名)(atribure)

c++ - 空析构函数与文字析构函数