Output is different for R-value and L-value. Why?
Posted
by
Leonid Volnitsky
on Stack Overflow
See other posts from Stack Overflow
or by Leonid Volnitsky
Published on 2012-09-01T09:28:33Z
Indexed on
2012/09/01
9:38 UTC
Read the original article
Hit count: 268
Can someone explain to me why output for R-value is different from L-value?
#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;
}
Output (same for gcc48 and clang32):
2
123
2
003
© Stack Overflow or respective owner