2

I don't understand how does this code compiles without at least a warning :

#include <string>
#include <iostream>

int main()
{
    const std::string a = "/42";
    const std::string &b = a.substr(1);

    std::cout << "A without slash is " << b << std::endl;
}

Because a.substr(1) returns a new std::string, b is taking a reference to a temporary lvalue and therefore is a dangling reference. Why does it work?

Brian Bi
  • 111,498
  • 10
  • 176
  • 312
Hugal31
  • 1,610
  • 1
  • 14
  • 27
  • `a.substr(1)` is an rvalue, but why it works anyway, I have no idea. – Tomáš Zato Aug 22 '19 at 15:55
  • 7
    Short version : `const` references can bind to and extend the lifetime of temporary objects in some circumstances. – François Andrieux Aug 22 '19 at 15:55
  • 1
    Also, just because it appears to give the result you wanted, doesn't mean it works. Dangling references can go unnoticed for ages. So be careful of your conclusions. Although in this case it does indeed work. – Lightness Races in Orbit Aug 22 '19 at 16:47
  • "therefore is a dangling reference" no it is not dangling and that's why there is no warning. There is even pesky MS extention that allows to bind rvalue to lvalue reference - that's dangerous, but fiortunately can be disabled. – Slava Aug 22 '19 at 16:47
  • You don't *store* anything in a reference. A reference just *refers to* (is an alias for) some other thing. That "other thing" is what actually stores something. And in some situations, a reference to a temporary can keep the temporary object alive for the lifetime of the reference. – Jesper Juhl Aug 22 '19 at 17:13

0 Answers0