【发布时间】:2019-11-11 05:55:32
【问题描述】:
考虑以下代码示例,为什么定义默认析构函数会导致编译错误?
#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 时,代码编译得很好。但我不明白为什么默认析构函数会有问题?
【问题讨论】:
标签: c++ dictionary destructor unique-ptr