What happens behind the scenes when initializing a const ref string member with a const char*

Viewed 60

If a const string is initialized from a const char*. I assume that a temporary std::string object is created and the reference refers to the temporary object. Is it correct?

#include<string>

struct A{
        const std::string& str_;
        A(const std::string& o):str_(o){}
};

int main(){

        A moshe{"moshe"};

}
1 Answers

Yes, a const std::string will be constructed from const char* and const std::string& field will refer to this temporary const std::string which has a scope of the constructor.

Normally a reference extends the lifetime of an object to its own lifetime when it's initialized, however this is an exception (cppreference)

Whenever a reference is bound to a temporary or to a subobject thereof, the lifetime of the temporary is extended to match the lifetime of the reference, with the following exceptions:

...

a temporary bound to a reference member in a constructor initializer list persists only until the constructor exits, not as long as the object exists. (note: such initialization is ill-formed as of DR 1696).

So the temporary const std::string will only be in a valid state for the time your struct is being constructed. The fact that standard permits it seems to be a known defect (bottom of this page).

Related