使用std :: map时,包含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;
}

编译器错误:

错误:调用“ Foo”的隐式删除副本构造函数

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

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

戴着帽子的公鸡

因为如果您自己定义析构函数,则编译器将不再为您生成copy-con和move-con。您可以将它们指定为默认值并删除(即使copy 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&&)

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

std :: unique_ptr析构函数构造函数顺序

使用unique_ptr保护的析构函数

为什么在使用unique_ptr时没有调用析构函数?

只需添加不执行任何操作都可能导致编译错误的析构函数(在std :: move附近),为什么?

为什么我会得到编译错误“使用删除的功能'std :: unique_ptr ...”

C ++ std :: unique_ptr存储在std :: map内部,使用删除的函数会形成不良

如何允许 std::unique_ptr 访问类的私有析构函数或使用私有析构函数实现 C++ 工厂类?

如何使用std:unique_ptr擦除包含结构的向量?

尽管类型在析构函数中完全合格,但std :: auto_ptr会导致崩溃和泄漏

std :: unique_ptr是否在其析构函数中将其基础指针设置为nullptr?

std::unique_ptr 在虚拟析构函数上重置 SIGABRT

thread_local std :: unique_ptr版本未调用析构函数

如果A有析构函数,std :: unique_ptr <A>什么时候需要特殊的删除器?

具有显式析构函数和std :: unique_ptr <>成员的类不能在std :: vector <>中使用吗?

在使用仅移动类型派生的类中定义析构函数时,使用std :: vector的emplace_back或push_back创建时会产生编译时错误

在移动构造函数中的unique_ptr上调用std :: move时出现“错误:使用已删除的函数”

奇怪的错误:当未真正创建指针时,使用删除的函数'std :: unique_ptr <_Tp,_Dp> :: unique_ptr

在具有受保护的析构函数的类中使用unique_ptr

在地图内使用unique_ptr时std :: pair中已删除的函数

使用 std::unique_ptr<T>::unique_ptr` 在 Visual Studio 2013 中构建错误

在C ++中定义和使用std :: map时发生编译错误

当包含它的对象调用其析构函数时,unique_ptr是否会取消分配?

为什么通过添加空的析构函数来修复“错误:使用unique_ptr将'sizeof'无效应用到不完整类型”的问题?

如何将包含 std::unique_ptr 的 std::optional 结构传递给函数?

声明包含std :: unique_ptr的结构的std :: vector类时出错

使用`std :: unique_ptr`时`std :: vector`中的数据不同

如何在结构上使用std :: unique_ptr?

使用std :: move(nullptr)的unique_ptr的operator =的C ++错误

使用std :: unique_ptr时出现内存泄漏