0

In c++17, it is valid like

string s = "asd";
string &ss = "asd" + s;  --> here

Now I have two doubts: 1.Why reference of ss is valid? What is it reference to? An anonymous variable of the result of "asd" + s?But is it valid to reference to an anonymous variable? 2.Why "asd" could directly add s?Wouldn't write it as string("asd") + s like before?Why?

f1msch
  • 509
  • 2
  • 12
  • I wouldn't say "valid", please note how some compilers complain about your snippet: https://godbolt.org/z/qh7TKG16T . Also, you may want to look at what [temporary lifetime extension](https://stackoverflow.com/questions/17362673/temporary-lifetime-extension) is. – Bob__ Jan 11 '23 at 09:11
  • Microsoft wins a prize again for being the only compiler that doesn't catch this very basic bug nest, with default command line options. – Michaël Roy Jan 11 '23 at 14:45
  • Oh. And "asd" doesn't add s, the function std::string operator+(const char*, const std::string&) is called. ss is left holding a reference to a dead r-value. You just have to **pray** that MS has some kind of proprietary mechanism to keep that alive. But praying is not considered good coding practice. – Michaël Roy Jan 11 '23 at 15:00

0 Answers0