Pergunta

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
Foi útil?

Solução

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.

Outras dicas

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

const std::string extension = it->path().extension().string();
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top