简体   繁体   中英

Strange behavior of reference in c++

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:

  1. Since reference of reference is not allowed, but vector::operator[] do return a reference of element inside container, why no error thrown?
  2. I know data::Get() function causes deep copy, but why I get the wrong value of a and b ? Will the return value be destroyed right after function call?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM