2

When I have a function like this:

std::vector<std::experimental::filesystem::directory_entry> Foo(const std::string& start)
{
    std::vector<std::experimental::filesystem::directory_entry> result;

    auto paths = std::experimental::filesystem::directory_iterator(start);

    for (auto& d : paths) {
        if (IsDirectory(d)) {
            result.push_back(d);
        }
    }

    return result;
}

is it required to perform a copy of directory entry when iterating over the paths collection with using auto d instead of auto& d?

My intuition says the following:

  1. While iterating paths returns a reference of std::experimental::filesystem::v1::directory_entry& type.
  2. Which I then pass to the vector whose push_back has the following signature: void push_back (const value_type& val)

Which I think means that after I return a vector from function it would contain elements that refer to the memory that already was reclaimed, hence I'm in trouble.

So the question: do I have to replace it with auto d or am I missing something?

zerkms
  • 249,484
  • 69
  • 436
  • 539

1 Answers1

4

No, push_back will do a copy to take ownership of the object.

As long as vector is declared to contain objects, regardless you can push_back with a reference, a const reference or an object, the vector will always store objects, never references.

jpo38
  • 20,821
  • 10
  • 70
  • 151