MathuSum Mut
MathuSum Mut

Reputation: 2825

How should class fields be declared in C++?

I need to declare and initialize a vector as a field of a class named PixelOperator.

I am torn between these two declaration methods, the first is "on the heap", and the second "on the stack" (or at least, that is my interpretation).

  1. vector<int>* field = new vector<int>();
  2. vector<int> field = vector<int>();

If I choose to declare in style number 1, I need to call delete in the destructor of the class.

Which one should I choose, and why?

Also, if the class is initialized on the heap (ie. PixelOperator* op = new PixelOperator();), are fields initialized on the stack initialized on the heap?

Upvotes: 0

Views: 81

Answers (3)

user7210680
user7210680

Reputation:

Your intuition is wrong in this instance. Approach (2) does not necessarily put the vector on stack. If PixelOperator object is declared locally and thus put on stack, the vector is put on stack as well, but if the PixelOperator object is put on heap using new operator, the vector also gets put on heap as part of that object. The difference in this instance would be that in approach (2) the vector is part of a contiguous block of memory together with other object fields, and in approach (1), the block of memory containing the object has in it address of another block of memory, which contains the vector. Of course, in approach (1) the vector ends up on heap regardless of whether the PixelOperator object is put on heap or on stack. Approach (2) is generally more desirable, as it allows for more transparency determining where the object gets allocated.

Upvotes: 2

SergeyA
SergeyA

Reputation: 62583

There is nothing to stumble on. There is never a reason to allocate std::vector<> (or any other standard container for that matter) on a heap. Simply never do this and you will be alright.

Upvotes: 1

Anon Mail
Anon Mail

Reputation: 4770

Choose method 2. That would put the object on the stack, but the vector's implementation will most likely put the contents on the heap.

Also, you have the meanings reversed. 1 is on the heap, 2 is on the stack. 1 will require delete.

Upvotes: 3

Related Questions