Home > front end >  Does the pointer in a class get deleted when the class gets deleted/destroyed?
Does the pointer in a class get deleted when the class gets deleted/destroyed?

Time:07-30

I'm new to C , and I want to know, does a pointer gets automatically deleted when the class gets deleted / destroyed? Here is an example:

class A
{
public:
   Object* b;
};

Will b get `deleted when the class is deleted?

CodePudding user response:

The object that the pointer points to will not be deleted. That is why it is a bad idea to use a raw pointer to refer to an object created with dynamic storage duration (i.e. via new) like this if the class object is intended to be responsible for destroying that object. Instead use std::unique_ptr:

#include<memory>

//...

class A
{
   public:
   std::unique_ptr<Object> b;
};

And instead of new Object(/*args*/) use std::make_unique<Object>(/*args*/) to create the object and a smart pointer to the object to store to b.

Or, most likely, there is no reason to use a pointer indirection at all. You can have a Object directly in the class. (This only really doesn't work if Object is meant to be polymorphic.)

CodePudding user response:

The memory reserved for the pointer itself is freed, so in that sense, b is 'deleted'. However, if b is not set to nullptr (any any object that b points appropriately dealt with) before b is deleted, then you will likely have a memory leak.

To sum up: the pointer itself will be deleted when the object is destroyed, but nothing will happen to the object that the pointer is pointing to. You will want to create an appropriate destructor to handle this.

CodePudding user response:

No, for the simple reason that nothing says that the pointer was used to allocate data: there is no implicit new in the constructor, and maybe the pointer is not used for dynamic allocation at all but for other purposes.

An extra reason is that in your use case it could be undesirable to delete the pointed data, which might be shared elsewhere for instance.

  • Related