考虑以下代码示例,为什么默认析构函数的定义会导致编译错误?
#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] 删除。
我来说两句