Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Idiomatic way to create a vector of pointers in C++11?

Let's say I want to create an std::vector of 10 pointers in C++11, each pointing to a default-constructed instance of class Foo. Here is one way to do it:

std::vector<Foo*> foos;
for (int i = 0; i != 10; ++i) {
    foos.push_back(new Foo());
}

Is there an idiomatic way to avoid the for loop?

like image 379
user1387866 Avatar asked Nov 28 '22 01:11

user1387866


1 Answers

If you want to avoid the explicit for loop, then yes, there is a way.

Use std::generate or generate_n:

std::generate_n(std::back_inserter(foos), 10, [] { return new Foo(); });

That looks idiomatic.

Well, loop or not, it is almost a choice. But raw pointers are not recommended anymore, because it is very difficult to avoid leaking them without RAII. Use smart pointers such as std::unique_ptr or std::shared_ptr depending on the need.

std::vector<std::unique_ptr<Foo>> foos;
std::generate_n(std::back_inserter(foos), 10, [] { return std::unique_ptr<Foo>(new Foo()); });

In C++14, you can use std::make_unique. So you can abondon new completely.

Hope that helps.

like image 131
Nawaz Avatar answered Dec 05 '22 11:12

Nawaz