据我记得,在调用任何函数之前,它会在堆栈中为函数结果和参数分配内存。
这是否意味着如果我有
T func()
{
T a;
return std::move(a);
}
我将仍然需要复制,因为已经为整个T分配了内存? 我还看到类似问题的解答中的内容。
return a;
与
是相同的。return std::move(a);
那么,我无法避免将内容复制到堆栈中吗?rvalue是堆栈中的值吗?
在某些地方使用它是否是一个好方法:
T a = std::move(func());
那么我应该避免复制函数的结果吗?我是否仍需要创建特殊的移动构造函数和移动操作符=?
我尝试测试它并获得了以下结果:
class Temp
{
public:
Temp()
{
cout << "construct" << endl;
i = 5;
}
~Temp()
{
cout << "destruct" << endl;
}
Temp(const Temp& t)
{
i = t.i;
cout << "copy construct" << endl;
}
Temp operator=(const Temp& t)
{
i = t.i;
cout << "operator =" << endl;
return *this;
}
int i;
};
Temp tempfunc1()
{
Temp t1;
t1.i = 7;
return t1;
}
Temp tempfunc2()
{
Temp t1;
t1.i = 8;
return std::move(t1);
}
int main()
{
Temp t1;
Temp t2;
t2.i = 6;
t1 = t2;
cout << t1.i << endl;
t1.i = 5;
t1 = std::move(t2);
cout << t1.i << endl;
cout << "NEXT" << endl;
t1 = tempfunc1();
cout << t1.i << endl;
cout << "NEXT" << endl;
t1 = std::move(tempfunc1());
cout << t1.i << endl;
cout << "NEXT" << endl;
t1 = tempfunc2();
cout << t1.i << endl;
cout << "NEXT" << endl;
t1 = std::move(tempfunc2());
cout << t1.i << endl;
}
结果如下:
construct
construct
operator =
copy construct
destruct
6
operator =
copy construct
destruct
6
NEXT
construct
copy construct
destruct
operator =
copy construct
destruct
destruct
7
NEXT
construct
copy construct
destruct
operator =
copy construct
destruct
destruct
7
NEXT
construct
copy construct
destruct
operator =
copy construct
destruct
destruct
8
NEXT
construct
copy construct
destruct
operator =
copy construct
destruct
destruct
8
是否使用std::move并不影响任何东西。或者说它只在存在特殊构造函数和析构函数时才有效?
为什么"t1 = t2"会调用拷贝构造函数和operator=函数两个方法?
非常抱歉提了这么多可能很简单的问题,即使我已经看了很多相关内容,也可能是因为我的英语不好,还需要一些解释。
提前感谢您的帮助。
operator=
来获取要复制的对象,然后再进行复制构造。 - Theolodisstd::move
的作用只是让左值看起来像右值(这应该暗示你在示例中不需要使用它)。因此,如果您想要特殊的右值引用行为,则需要一个右值引用重载。 - juanchopanza