0

This is a question about scope of arrays inside std::vector member structures.

Suppose I have next code:

struct memberStruct {
...
char array[5];
...
};

std::vector <memberStruct> _workVector;

The question: Which of vector clear methods (clear/erase/pop_back) ensure memberStruct.array de-allocation AKA going out of scope?

BaruchLi
  • 895
  • 2
  • 10
  • 17

3 Answers3

5

The member array is part of the enclosing structure memberStruct, there is no need to allocate or deallocate it. The vector will allocate/deallocate instances of memberStruct and that will take care of the members inside these instances as well.

Daniel Frey
  • 52,317
  • 11
  • 110
  • 168
  • OK. And will `push_back(localStaractVar)` method and `[] operator` call copy constructor? – BaruchLi Nov 03 '13 at 14:23
  • @BaruchLi `push_back` will *use* the copy-ctor of `memberStruct`. Each type (`class` or `struct`) can have either a default-generated copy-ctor or a user-defined one. Maybe [this FAQ](http://stackoverflow.com/questions/4782757) helps. – Daniel Frey Nov 03 '13 at 14:27
2

array will be part of the memberStruct. This struct will be 5 bytes + other members + padding. So the answer to your question is: every method you mention will do the trick.

Evgeny Lazin
  • 8,533
  • 5
  • 39
  • 82
2

Think of

...
char array[5];
...

as equivalent to

...
char array_0;
char array_1;
char array_2;
char array_3;
char array_4;
...

and things may become clear.

This is very different from

char *array = new char[5];

where the five bytes are stored outside your struct, and do need special handling.