What follows represents what usually happens in C++. At the end I cover some possible reasons why it may not be the case.
Usually, when you write MyClass *clz = new MyClass();
, the new
operator will allocate sizeof MyClass
bytes on the heap, call the constructor of its member and return a pointer to the allocated memory.
As you're including the vector
as a member, any members of the vector will be included in the sizeof MyClass
heap allocation. This is implementation dependent but is usually a size, capacity and a pointer to another heap allocation which is used for a variable sized array of MyOtherClass
es. In other words, you may get 2 heap allocations with the original new
.
If, however, you just included MyClass clz;
as a local variable, the sizeof MyClass
will be allocated on the stack. The valriable array within the vector
may still be allocated on the heap however.
But, this being C++, the above may not be true. Firstly, one can override the new
operator to do something else. In theory you could make it allocate on the stack, using alloca
say, though this would be a spectacularly bad idea.
Secondly, the implementation of std::vector
can vary considerably. One optimisation, known as the small vector optimisation, stores a few objects in its struct rather than on the heap if it can. Under certain circumstances this can improve performance though is probably unlikelty in your case (depends on the implementation of vector
and MyOtherClass
). Also, and more likely in your case, the implementation may not do an internal heap allocation until you insert something. So the new MyClass
doesn't do 2 heap allocations but you may well get one or more as you fill the vector in the running program.
std::vector
itself is an object that contains a pointer to an array. Thus, the "vector" object (the object of class std::vector) is on the stack insideMyClass
, while the internal array that the vector points to is on the heap.