I'm little confused about reference type in c++, here goes my code snippet.
class data
{
public:
std::vector<int> Get() const
{
return vec;
}
private:
std::vector<int> vec = {1,2,3,4};
};
int main()
{
data dat;
auto const& a = dat.Get()[1];
auto const& b = dat.Get()[2];
std::cout << "a = " << a << ", b = " << b << std::endl;
return 0;
}
The output a = 0, b = 1433763856 doesn't make any sense, after I remove the leading & before a and b, everything works fine. Now here goes my questions:
- Since reference of reference is not allowed, but
vector::operator[]do return a reference of element inside container, why no error thrown? - I know
data::Get()function causes deep copy, but why I get the wrong value ofaandb? Will the return value be destroyed right after function call?