Does calling a function on a temporary that returns a ref to that temporary result in accessing a dangling ref?
I have this code:
std::filesystem::path;
std::string filename;
// ...
if (auto full_path = (path / filename).make_preferred().u8string();
is_media_file(full_path))
{
// ...
}
This calls make_preferred() on the temporary (path / filename) and returns a reference to itself. I then call u8string() on it. Is that valid? Or has the temporary gone away by the time u8string() is called?
Posted Feb 19, 2022, 4:49 PM UTC
The result of the expression will live until the end of the statement, i.e. until the
;.OK. I was worried because of code like this:
which has the purpose of preventing some common cases of dangling references. Since
std::filesystem::pathdoes not use this idiom it seemed like I might be running into a dangling ref case.That pattern is only relevant in the case of
const auto& s = foo{}.str();
That would in fact result in
sbeing a dangling reference unless that overload pattern was used.In any case, the
foo{}temporary will live until the end of the statement.It doesnt, because it doesnt need to.
If you chain
make_preferredin an expression like this, it works since the object is still alive. and the.string(and friends) member functions return by value anyways, so thats not an issue either.