Reference to a temporary vs Pointer to temporary and their lifetime

Viewed 341

I have read many articles regarding the lifetime of a temporary and it seems the lifetime of temporary object is extended in certain cases, while in the rest of the cases, its a dangling object.

In my case the temporary object is returned from a function, I want to understand if the const ref to the temporary object will remain valid or not.

Here is the code:

class MyClass
{
public:
    std::vector<int> vec{ 1, 2 };

    MyClass()
    {
        cout << "Ctor" << endl;
    }

    MyClass(const MyClass &copy)
    {
        vec = copy.vec;         
        cout << "Copy Ctor" << endl;
    }

    ~MyClass()
    {
        cout << "Dtor" << endl;
    }
};

MyClass access()
{
    MyClass obj;
    obj.vec[0] = 10;
    return obj;
}

int main()
{
    {
        const auto &ret = access();             // calls the copy-ctor and assigns the temporary to reference 'ret'
        auto val = ret.vec[0];
        cout << "By Ref = " << val << endl;     // works fine
    }

    cout << "_____________________________________" << endl;

    {
        const auto *ret = &access();            // temporary is lost 
        auto val = ret->vec[0];                 // program crash
        cout << "By Pointer = " << val << endl; 
    }

    return 0;

}
1 Answers

Only temporaries bound to const references have their lifetime extended, with the exception of const references bound to return of functions, such as

const int& f(){int x{42}; return x;}
int main()
{
    const int& bad = f(); // you'll end up with a dangling reference
}

or

const int& f(const int& x)
{
    return x;
}
int main(){
{
    const int& bad = f(42); // you'll end up (again) with a dangling reference
}

In your second case you have a pointer, so the lifetime of the right hand side temporary is not prolonged.

Related