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?