【发布时间】:2016-03-13 15:19:57
【问题描述】:
对于下面的程序代码,我必须在接收右值和左值引用的一对成员函数中编写相同的代码。
我的目标是只使用一对中的一个(例如;只使用接受右值的那些),以及其他的。看了std::forward的参考资料,据我了解,好像是为了这个目的。但是,当我删除左值引用时,会出现以下编译器错误。
'TestClass::TestClass(const TestClass &)': 无法将参数 1 从 'std::wstring' 转换为 'std::wstring &&'
如何防止这种代码重复?
#include <iostream>
#include <string>
class TestClass
{
public:
TestClass(const std::wstring & Text)
: Text(Text)
{
std::wcout << L"LValue Constructor : " << Text << std::endl;
/*Some code here...*/
}
TestClass( std::wstring && Text)
: Text(std::forward<std::wstring>(Text))
{
std::wcout << L"RValue Constructor : " << this->Text << std::endl;
/*Same code here...*/
}
TestClass(const TestClass & Another)
: Text(Another.Text)
{
std::wcout << L"Copy Constructor : " << Text << std::endl;
/*Some code here...*/
}
TestClass( TestClass && Another)
: Text(std::forward<std::wstring>(Another.Text))
{
std::wcout << L"Move Constructor : " << Text << std::endl;
/*Same code here...*/
}
private:
std::wstring Text;
};
int wmain(int argc, wchar_t *argv[], wchar_t *envp[])
{
std::wstring Argument(L"Testing Copy");
TestClass Class1Copy(Argument);
TestClass Class1Move(L"Testing Move");
TestClass Class2Copy(Class1Copy);
TestClass Class2Move(std::move(Class1Move));
_wsystem(L"pause");
return 0;
}
输出:
LValue Constructor : Testing Copy
RValue Constructor : Testing Move
Copy Constructor : Testing Copy
Move Constructor : Testing Move
Press any key to continue . . .
【问题讨论】:
-
Text(std::forward<std::wstring>(Text))应该是Text(std::move(Text))。在您使用forward而不是move的其他地方也是如此。
标签: c++ c++11 move-semantics rvalue-reference move-constructor