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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With