Aquarius_Girl
Aquarius_Girl

Reputation: 22936

When a already existing pointer is pushed in a stack, does its copy gets created?

void deleteAllNodes ()
{
    stack <parentBranch *> mystack;

    // `trunk` is the existing head node
    mystack.push (trunk);

    cout << mystack.top ()->content;
}

In this case a "copy" of trunk gets pushed in the stack? So, does this means that at a time there are two trunks present in the memory?

Upvotes: 0

Views: 161

Answers (3)

Alok Save
Alok Save

Reputation: 206566

No there is only one trunk but two pointers pointing to it.

This is the reason, Standard Library containers do not take ownership of deallocating memory of pointer members, because they cannot determine who actually owns the object being pointed to, the pointer which resides inside the container or the one which was used for push operation.

If you are using an pointer as container element, you are forced to do the manual memory management, it is up to the user to ensure the pointed to object remains valid.
This is the reason one should use smart pointers and not raw pointers with Standard Library containers, it saves you the manual memory management.

If the element being pushed in is not an pointer but an object then there will be two separate copies of the object, One which gets stored in the container and another which was used for push in to the container.

Upvotes: 3

Managu
Managu

Reputation: 9039

Nope. trunk points to an object, but isn't the object itself. Like a sign that reads "Car -->" next to a car. When you push trunk onto mystack, you don't get another car. You just get another sign pointing to the same car.

Woe be it if you drive the car off (i.e. delete trunk;). Then you'll have a whole bunch of signs that point to a car, but when someone comes along and tries to get in that car, they'll fall flat on their rear. All the signs pointing to the car will be liars.

Upvotes: 4

Blagovest Buyukliev
Blagovest Buyukliev

Reputation: 43538

A copy of the pointer gets pushed, but not a copy of the object it points to.

Upvotes: 3

Related Questions