1

当我遇到这种情况时,我正在追踪一个编译错误:

struct Y        
{               
  int&& y;      
  Y(int&& y)    
    : y(y)      
  {             
  }             
};              

struct ZZ {};   
struct Z        
{               
  ZZ&& z;       
  Z(ZZ&& z)     
    : z(z)      
  {             
  }             
};

这些都失败了:

exec.cpp: In constructor ‘Y::Y(int&&)’:
exec.cpp:57:10: error: invalid initialization of reference of type ‘int&&’ from expression of type ‘int’
exec.cpp: In constructor ‘Z::Z(ZZ&&)’:
exec.cpp:67:10: error: invalid initialization of reference of type ‘ZZ&&’ from expression of type ‘ZZ’

但我不确定为什么。这里有什么问题?

我将 g++4.5.3 与 -std=gnu++0x 选项一起使用,但它也与 -std=c++0x 选项一起使用。

4

2 回答 2

2

你需要说: y(std::move(y))。这是获得可以绑定到右值引用的表达式的唯一方法。只是裸表达式y是左值。

(请注意,存储引用类成员非常危险且难以纠正。)

于 2013-05-25T15:15:16.827 回答
2

任何有名字的东西都是左值。这意味着构造函数参数y是一个左值(类型为右值引用int),因为它有一个名称“ y”。

用于std::move(y)将其转回 r 值。

于 2013-05-25T15:16:06.110 回答