【发布时间】:2016-01-02 08:44:24
【问题描述】:
我通过在它们上应用std::move 和std::forward 来尝试一个关于通用引用的程序。直到今天,我都认为两者是相同的,但在这个程序(如下所示)中,输出让我感到惊讶。
#include <iostream>
#include <string>
#include <utility>
using namespace std;
class X
{
string take="";
public:
template<class T>
void pass1 (T &&str) // str is a universal reference as it can bind to anything, both rvalue and lvalue references
{
take=move(str);
}
template<class T>
void pass2 (T &&str)
{
take=forward<T>(str);
}
void show()
{
cout<<"take = "<<take<<"\n";
}
}obj;
int main()
{
cout<<"using move on universal reference:-\n";
string str="he is there";
cout<<"str = "<<str<<'\n';
obj.pass1(str);
obj.show();
if (str.empty())
cout<<"str is empty\n\n";
else
cout<<"str isnt empty\n\n";
cout<<"using forward on universal reference:-\n";
str="he was there";
cout<<"str = "<<str<<'\n';
obj.pass2(str);
obj.show();
if (str.empty())
cout<<"str is empty\n\n";
else
cout<<"str isnt empty\n\n";
return 0;
}
输出:
using move on universal reference:-
str = he is there
take = he is there
str is empty
using forward on universal reference:-
str = he was there
take = he was there
str isnt empty
*/
我的问题是:
- 为什么输出不同?
-
move和forward工作不相似吗?它们的工作方式有何不同(在上述代码的上下文中)?
【问题讨论】:
-
将
move与右值引用一起使用,将forward<T>与转发(“通用”)引用一起使用。 -
问题是什么?