如何使具有 unique_ptr 成员的类与 std::move 和 std::swap 一起使用? [英] How to make a class with a member of unique_ptr work with std::move and std::swap?
本文介绍了如何使具有 unique_ptr 成员的类与 std::move 和 std::swap 一起使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一堂课.它有一个 unique_ptr 成员.
I have a class. It has a member of unique_ptr.
class A
{
std::unique_ptr<int> m;
};
我希望它适用于以下语句
I hope it works with the following statements
A a;
A b;
a = std::move(b);
std::swap(a, b);
如何制作?
根据评论,我有一个问题.这个编译器依赖吗?如果我什么都不做,它就无法通过 VC++ 2012 中的编译.
我以前试过
struct A
{
A() {}
A(A&& a)
{
mb = a.mb;
ma = std::move(a.ma);
}
A& operator = (A&& a)
{
mb = a.mb;
ma = std::move(a.ma);
return *this;
}
unique_ptr<int> ma;
int mb;
};
但不确定这是否是最好和最简单的方法.
But not sure if this is the best and simplest way.
推荐答案
你的第一个例子在 C++11 中是绝对正确的.但是 VC++ 2012 目前没有实现 N3053一>.因此,编译器不会为您隐式生成移动构造函数或赋值运算符.因此,如果您坚持使用 VC++ 2012,则需要自己实现它们.
Your first example is absolutely correct in C++11. But VC++ 2012 currently doesn't implement N3053. As a result, the compiler does not implicitly generate move constructor or assignment operator for you. So if you stuck with VC++ 2012 you need to implement them by yourself.
这篇关于如何使具有 unique_ptr 成员的类与 std::move 和 std::swap 一起使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文