Reputation: 563
I'm wondering when objects of classes allocate dynamic memory. Take the following statements, dealing with a class called "test":
test* pd = new test(2); // Creating a test object on the free store, and storing it in a pointer.
test ob(2); // Creating a test object, in stack memory (?)
I suspect only the first line creates an object in dynamic memory (and thus would have to be deallocated eventually by the programmer), while the second line only creates an object in stack memory due a lack of the keyword "new" (and would not have to be deallocated by the programmer).
Upvotes: 0
Views: 2107
Reputation: 979
Your example is roughly correct.
test* pd = new test(2);
The new keyword will make the compiler allocate memory on the heap for a new test object. It is equivalent to calling malloc(size) in the C language. In languages (like C and C++) without an implicit garbage collector, you are then responsible for deleting the object later.
In some short-run programs you can get away with not deleting the object, since the memory allocated by the process should be freed when your process exits in a modern machine. But that's really inelegant and should not be your habit.
It is also important not to think of test*pd = new test(2);
as storing a test object in the *pd pointer. The pointer is only pointing to it, and you can make the pointer point to other things later. The pointer has nothing to do with the new test object except that right now it happens to be pointing at it.
test ob(2);
Here, because you did not use the new keyword or otherwise allocate memory on the heap, the compiler is responsible for allocating the memory for the object--and for deleting it or forgetting about it when it falls out of scope. The stack is an ordinary way to do that, but I believe the method is technically compiler-dependent and there might be some cases where particular compilers stored the variable elsewhere.
Upvotes: 2