使用std :: map时,包含unique_ptr的结构中的默认破坏者会导致编译错误

default destructor in a struct containing a unique_ptr causes compilation errors when using an std::map

本文关键字:破坏者 默认 错误 编译 结构 ptr map std 包含 unique 使用      更新时间:2023-10-16

考虑以下代码示例,为什么默认破坏者的定义会导致编译错误?

#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;
}

编译器错误:

错误:致电" foo"的隐式删除复制构造函数

从错误消息中,我得到有一个无声的副本正在发生?

值得一提的是,使用普通指针而不是unique_ptr时,代码会罚款。但是我不明白为什么默认的破坏者会成为问题?

,因为如果您自己定义了灾难,那么编译器将不再为您生成复制子和Move-con。您可以将它们指定为默认值并删除(即使复制con仍将被隐式删除unique_ptr的原因(,并且您的代码将再次工作:

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&&)也是这种情况。