使用std :: map时,包含unique_ptr的结构中的默认破坏者会导致编译错误
default destructor in a struct containing a unique_ptr causes compilation errors when using an std::map
考虑以下代码示例,为什么默认破坏者的定义会导致编译错误?
#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&&)
也是这种情况。
相关文章:
- 如何创建一个CMake变量,除非显式重写,否则使用默认值
- 如何使用默认参数等选择模板专业化
- 具有默认模板参数的多态类的模板推导失败
- 为什么在没有显式默认构造函数的情况下,将另一个结构封装在联合中作为成员的结构不能编译
- 当函数模板参数是具有默认参数的类模板时,函数模板参数的推导如何执行
- 初始化具有非默认构造函数的std::数组项的更好方法
- 何时提供默认参数作为模板参数
- 是默认情况下分配给char数组常量的值
- 具有默认值的引用获取函数
- 具有默认模板类型的默认构造函数的类型推导
- 当给定默认值时,为什么此模板参数推导失败
- 修改 VS Code 中的默认C++代码段
- 声明默认的模板化函数
- 将const引用参数初始化为默认参数会导致悬空引用吗
- 如何使用非默认构造函数实例化模板化类
- 如何修复带有 clang 的参数'args'缺少默认参数的问题?
- 从具有默认值的部分指定模板类继承时发生SWIG错误,具有不带默认值的正向声明
- 为什么大多数 pair 实现默认不使用压缩(空基优化)?
- 使用std :: map时,包含unique_ptr的结构中的默认破坏者会导致编译错误
- 在类实现中为字符串的覆盖默认破坏者