Omkar Somani
Omkar Somani

Reputation: 101

Will data members on a heap-allocated object be allocated on the heap or the stack?

I am allocating a class object on heap, so all the data members will be on heap. But what if my class contains some data structure (e.g. std::vector) as a member:

#include <vector>

class Temp
{
public:
    std::vector<double> m_dPtList;
};

int main()
{
    Temp* pTemp = new Temp;
    pTemp->m_dPtList.Add(10.0);
    pTemp->m_dPtList.Add(20.0);
    pTemp->m_dPtList.Add(30.0);

    return 0;
}

Will the values 10.0, 20.0, and 30.0 be stored on the heap or on the stack?

Upvotes: 0

Views: 816

Answers (3)

Tony Delroy
Tony Delroy

Reputation: 106246

In your code, Temp's just wrapping std::vector. You use new to create the Temp object, so it goes on the heap. That object itself can be expected to contain a pointer to the memory in which the vector will store the data added to it... that will also be on the heap. Summarily, only the pTemp pointer itself is on your stack.

Upvotes: 0

XAder
XAder

Reputation: 676

pTemp is on the Heap. You add into vector through value, so value is added into vector, vector on its own allocates storage on the heap. Case when contents would be on the stack is:

Class Temp
{

std::vector<double *> m_dPtList;

}

double temp = 10.0;
Temp* pTemp = new Temp();

pTemp->m_dPtList.Add (&temp);

Upvotes: 2

user541686
user541686

Reputation: 210755

vector's buffer is always allocated on the heap, but in general, it's however the object was designed to be -- the immediate members will be allocated in the same place, but God knows where embedded pointers would point to.

Upvotes: 1

Related Questions