The c++17 standard §15.2 point 6.9 says
- temporary object bound to a reference parameter in a function call (8.5.1.2) persists until the completion of the full-expression containing the call
So you are good. No UB here auto x= A("E")._s
.
The other issues you have described well yourself. After construction accessing the member will be UB.
You can, however, extend the lifetime of a temporary object by binding it to a local const-reference like so:
struct A {
const std::string& _s;
A(const std::string& s) : _s(s) {}
};
int main(void) {
const std::string& e = "E";
A a(e);
std::cout << a._s << '
';
}
which would not be UB, but I would not use it like this.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…