【发布时间】:2016-11-07 08:28:39
【问题描述】:
根据我的理解,下面的代码应该调用 Test 类的移动构造函数,因为这个函数是按值返回的,这意味着表达式 GetTestObj() 应该是右值并且 xvalues 被隐式移动但是为什么这段代码调用复制构造函数?
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;)并返回它?
标签: c++ c++11 c++14 move xvalue