按下面的代码应调用Test
类的移动构造函数,因为该功能是由价值回归我的理解,这意味着表达GetTestObj()
应该是右值和xvalues都隐含移动,但为什么这个代码是调用拷贝构造函数?函数返回值的值类别总是xvalue?
class Test
{
public:
Test()
{
}
Test(const Test& arg)
{
std::cout<<"Copy Constructor Called..."<<std::endl;
}
Test(Test&& arg)
{
std::cout<<"Move Constructor Called..."<<std::endl;
}
};
Test GetMyTestObj()
{
Test *ptr = new Test();
return *ptr;
}
Test dummy = GetMyTestObj(); //Copy Constructor Called...
它非常依赖'Test'类的定义。你有没有尝试使复制构造函数被删除?你有一个移动构造函数?你知道你在显示的代码中有内存泄漏吗?为什么不简单地在函数中创建一个简单的'Test'对象实例(例如'Test test;')并返回它? –