Pregunta

Why is there a dangling reference in the following code? I've thought that references to const always extend the lifespan of a temporary to their scope.

boost::filesystem::recursive_directory_iterator it(dir_name);
const std::string& extension = it->path().extension().string();
std::cout << extension << std::endl; // error, dangling reference
¿Fue útil?

Solución

From the documentation for class path:

Member functions described as returning const string are permitted to return const string&

So there's no guarantee that string() actually returns a temporary string. It may be a reference to a string inside the temporary path returned by extension(); that will not have its lifetime extended, since it is not directly bound to a local reference.

Otros consejos

Don't make extension a const ref. Do this instead:

const std::string extension = it->path().extension().string();
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top