Since I wasn't satisfied with the answers, and hope that the sameer karjatkar wants to learn more than just a simple yes/no answer, here you go.
Typically a process has 5 different areas of memory allocated
- Code - text segment
- Initialized data – data segment
- Uninitialized data – bss segment
- Heap
- Stack
If you really want to learn what is saved where then read and bookmark these:
COMPILER, ASSEMBLER, LINKER AND LOADER: A BRIEF STORY (look at Table w.5)
Anatomy of a Program in Memory
I'll start from the beginning...
Vector** v = new Vector*[100];
Allocates an array of 100 pointers to objects of type Vector on the heap
It returns one pointer- v - the you can use to keep track of this array of pointers.
Delete this array of 100 points with:
delete[] v;
(Use the delete
operator- delete
for a single allocated object, delete[]
for an array)
Next case (I'm assuming you mean new Vector[100]
:
Vector* v = new Vector[100];
You allocated an array of 100 Vectors on the heap and got a pointer to its start location- v.
Delete this array with:
delete[] v;
Next...
class Vector
{
int x, y, z;
}
Vector* v = new Vector();
This allocates an object of class Vector on the heap and gives you a pointer to keep track of it. Because you allocated the entire object on the heap, x, y, and z are all allocated on the heap.
Delete it with:
delete v;
class Vector2
{
int items[10];
}
Vector2* v2 = new Vector2();
This one is a bit trickier but I'm going to reason it out...
Classes are blueprints. You haven't allocated any memory at all until you instantiate the class somehow, in this case on the heap. Because the class is a blueprint, items
could not have been allocated until you created an object of class Vector2
on the heap. I think we can reasonably infer that items
is thus allocated on the heap.
Delete v2 with:
delete v2;
And finally:
class Vector3
{
int* items;
}
Vector3 v3 = Vector3();
You allocated all of class Vector3 on the stack, the pointer inside of it items
is also allocated thus. Nothing went on the heap, so don't delete it.
Best Answer
... is that you have to do memory allocation manually. But let's leave that aside:
Note that in the second rule, by "large object" I mean something like
but not
since the second is actually a very small object wrapping a pointer to a heap-allocated buffer.
As for pointer vs. value members:
The use of smart pointers is of course recommended where appropriate. Note that you can use a reference in case of heap allocation because you can always
delete &ref
, but I wouldn't recommend doing that. References are pointers in disguise with only one difference (a reference can't be null), but they also signal a different intent.