This code will explode, right? As soon as the loop exits, the original instances will die with all their inner members so if they weren't PODs, any method like do_stuff
which requires access to members of B
will throw a segmentation fault, correct?
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 any way to do this without using a pointer? Or do you have 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];
}
The first code example is valid.
std::vector
will make a copy of the objects you pass them with push_back
(or will move them in place with C++11 if you're pushing a temporary) and it will keep all of the instances alive as long as the vector itself is alive.
The destruction will happen when you exit the function, not when you exit the loop.
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