【发布时间】:2012-09-01 09:28:33
【问题描述】:
有人可以向我解释为什么 R 值的输出与 L 值不同吗?
#include <iostream>
#include <vector>
using namespace std;
template<typename Ct>
struct ct_wrapper {
Ct&& ct; // R or L ref
explicit ct_wrapper(Ct&& ct)
: ct(std::forward<Ct>(ct)) { std::cout << this->ct[1];};
};
int main() {
// L-val
vector<int> v{1,2,3};
ct_wrapper<vector<int>&> lv(v);
cout << endl << lv.ct[0] << lv.ct[1] << lv.ct[2] << endl;
// R-val
ct_wrapper<vector<int>&&> rv(vector<int>{1,2,3});
cout << endl << rv.ct[0] << rv.ct[1] << rv.ct[2] << endl;
}
输出(gcc48 和 clang32 相同):
2
123
2
003
回答
它在我与 Johannes Schaub 的聊天中被埋没了,所以我把它放在这里。
当临时向量初始化 r-value-ref 成员变量rv.ct 时,临时生命周期没有延长,因为有一个特殊的例外:[class.temporary]p5:“在构造函数的ctor-中临时绑定到引用成员-初始化程序 (12.6.2) 一直存在,直到构造函数退出。”
【问题讨论】:
标签: c++ c++11 rvalue-reference perfect-forwarding