Skip to main content
gamedev.net
🔒 Locked

[C++] Memory allocation question

Started by sheep19 Nov 24, 2011 at 11:38 PM 3 replies 1k views
Original Post
sheep19
sheep19
Hi. I have a structure that represents a node in a linked list:


template <class T>

struct Foo
{
public:
Foo()
{
name = new string;
age = 10;
}

~Foo()
{
delete name;
}

private:
Foo(const Foo&);
Foo &operator = (const Foo &);

string *name;
int age;

};

struct Node
{
T data;
Node<T> *next;
};


Node *n = new Node;

Now the space has been allocated on the heap.The name(string name) of the Foo object is allocated on the heap. Even if n was created on the stack, Foo::name would be still allocated on the heap.
But what is the case of Foo::age when n is allocated on the heap? Is it allocated on the heap or on the stack?
Hodgman
Hodgman
age is a part of the Foo object, so when you allocate a Foo object, you're allocating age.
kilah
kilah
The whole object is allocated in the heap, Foo::age too. Think that the size of your object is what the allocation request is about, that includes Foo::age. What it is going to happen is that you have 2 allocations on heap per object in this case. That means first allocation is sizeof( Foo) = sizeof(age) + sizeof(name), and second allocation sizeof(string) for name pointer. (In fact there is going to be even more allocations due to std::string but that's another story)
alvaro
alvaro
Why is name a pointer? And how come "template" appears before a class definition that doesn't use T?
dpadam450
dpadam450
The variable n by itself is just a pointer (32/64bit address). The pointer is on the stack, the object it points to is on the heap.

Node *n = new Node;
n = new Node;

Here you would have just changed the variable n (on the stack) to hold a different address. The two Foo objects are still on the heap.
NBA2K, Madden, Maneater, Killing Floor, Sims 

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.