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 ofa
andb
? Will the return value be destroyed right after function call?
CodePudding user response:
You return a copy of the vector, as the signature
std::vector<int> Get() const
implies, as opposed to
std::vector<int> /*const*/& Get() const
which would return a reference, this is true, but that doesn't really explain why returning a copy is a mistake in this situation.
After all, if the call was
auto const& v = data.Get(); // *your* version here, the one returning by copy
v
would not be dangling.
The point is that you're not keeping that copy alive by bounding it to a reference (as I've done in the last snippet).
Instead, you're calling operator[]
on that temporary, and that call results in a reference to the value in the vector, an int&
. When the temporary vector returned by dat.Get()
is destroyed, that's the reference which dangles.
If operator[]
returned by value, then not even the a
and b
in your example would dangle.