Question

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
Was it helpful?

Solution

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.

OTHER TIPS

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

const std::string extension = it->path().extension().string();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top