Is it impossible to build instances in a loop without a pointer?

This code will explode, right? Once the loop exits, the original instances will die with all their internal elements, so if they are not do_stuff , any method, such as do_stuff that requires access to members of B , will throw a segmentation error, right?

 void foo() { std::vector<B> bar; for (int i = 0; i < 7; i++) bar.push_back(B(i, i, i)); bar[3].do_stuff(); } 

So, is there a way to do this without using a pointer? Or you need to do this:

 void foo() { std::vector<B*> bar; for (int i = 0; i < 7; i++) bar.push_back(new B(i, i, i)); bar[3]->do_stuff(); for (int i = 0; i < 7; i++) delete bar[i]; } 
+7
c ++
source share
4 answers

The first code is better than the second.

Instances of B will be moved because C ++ 11 / is copied from pre-C ++ 11 to the vector, so they will not exit the field after the loop - only after the vector falls out of scope.


If you want to get absolutely optimal performance, do the following:

 void foo() { std::vector<B> bar; bar.reserve(7); for (int i = 0; i < 7; i++) bar.emplace_back(i, i, i); bar[3].do_stuff(); } 

This guarantees only one redistribution, and elements are created directly inside the vector (instead of moving or copying them there) according to Marc Glisse's comments.

+7
source share

The first code example is valid.

std::vector will make a copy of the objects that you pass to them using push_back (or will move them to their place with C ++ 11 if you press temporary), and it will keep all instances alive as long as the vector itself is alive .

Destruction will occur when you exit a function, and not when exiting a loop.

+12
source share

No, std::vector takes responsibility for its members, so the source code will work fine.

+4
source share

std::vector copies the objects provided to it (for example, push_back() ) and saves them until the vector itself is destroyed.

So, the first code is completely fine if the copy constructor B ( B(const B&) ) is implemented correctly.

+3
source share

All Articles