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.
Case I:
Note that,
For example,
Here the reference
myRefextend the lifetime of the temporaryintthat was materialized using the prvalue expression 5 due to temporary materialization.Similarly in your first code snippet, the function
getString()returns astd::stringby 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
No there are other examples like the one i have given(
const int &myRef = 5;).