【发布时间】:2015-08-22 06:28:18
【问题描述】:
我想知道我对问题的理解是否正确,如果是,如何解决。
我正在编写一个模板类来存储许多类型对象并对它们执行操作。问题是我的技能仍然很差,所以即使在阅读11 pages about rvalues 之后我也不完全明白。在我的模板类中,如果我理解正确,一个重载的右值复制函数将使它成为主函数中的代码,当行'cout
如果正确,如何正确实现右值对象复制功能?我能够做到这一点的主要兴趣是创建一个正确接受右值的构造函数,而不是像我的左值构造函数那样基本上工作,而迂回的方法是确保我理解它。
template<class T>
class Vec3
{
public:
Vec3(){}
Vec3(const Vec3 &vec):x(vec.x),y(vec.y),z(vec.z){}
void operator = (const Vec3 &other)
{x=other.x; y=other.y; z=other.z;}
// void operator = (Vec3 &&other)
// {
//this would just call the other overloaded copy function
// *this = move(other);
// }
T x, y, z;
};
main(){
Vec3<int> ex(0,0,0);
Vec3<int> test = move(ex);
test.z++;
cout << test.z;//will be 1
cout << ex.z;//will be 0
}
【问题讨论】:
-
Vec3
test = move(ex);不会触发 operator=,它会触发复制构造函数。你应该有右值复制构造函数而不是 operator=. -
复制构造函数是什么样的? 'Vec3(Vec3 &&vec){/*类似于 this=vec?*/}'
-
除非
x、y和z有什么特别之处,否则最好让编译器为您生成复制和移动函数。 (除非您使用不生成移动功能的 Visual Studio 2013)
标签: c++ c++11 rvalue-reference