Home > Software design >  Why is temporary object living after end of the expression
Why is temporary object living after end of the expression

Time:11-23

Why if

string getString(){
    return string("string");
}

int main(){
const string& a = getString();
    cout << a;
}

Will give an UB

This:

class vector{
void push_back(const T& value){
        //...
        new(arr   sz) T (value);
          sz;

    }
}

main(){
vector v;
v.push_back(string("abc"));
}

will be OK?

I guess that in first case temporary object expires right after end of the expression const string& a = getString(); Whereas in second case temporary object's life will be prolonged until finish of the function. Is it the only one case of prolonging of temporary object's life behind of an expression.

CodePudding user response:

Case I:

I guess that in first case temporary object expires right after end of the expression const string& a = getString();

Note that,

const references are allowed to bind to temporaries. Also, const references extend the lifetime of those temporaries.

For example,

const int &myRef = 5;

Here the reference myRef extend the lifetime of the temporary int that was materialized using the prvalue expression 5 due to temporary materialization.

Similarly in your first code snippet, the function getString() returns a std::string by value. The lifetime of the temporary that is materialised in this case will also be extended.

So your first code snippet has no UB.

You asked

Is it the only one case of prolonging of temporary object's life behind of an expression.

No there are other examples like the one i have given(const int &myRef = 5;).

  • Related