Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it not possible to construct instances in a loop without a pointer?

Tags:

c++

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];
}
like image 713
AturSams Avatar asked Aug 30 '15 17:08

AturSams


1 Answers

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.

like image 106
6502 Avatar answered Nov 03 '22 00:11

6502