2

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?

Remy Lebeau
609k36 gold badges516 silver badges875 bronze badges
asked Jul 29, 2022 at 19:46
3
  • 2
    No, nothing is done. That's why smart pointers were added to the standard library Commented Jul 29, 2022 at 19:47
  • 2
    Use a smart pointer to get transitive destruction. Commented Jul 29, 2022 at 19:48
  • Yes, but if you have assigned the pointer to some other variable in the meanwhile, you will have a memory leak. Commented Jul 29, 2022 at 19:48

3 Answers 3

3

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.)

answered Jul 29, 2022 at 19:51
Sign up to request clarification or add additional context in comments.

Comments

1

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.

answered Jul 29, 2022 at 19:52

Comments

0

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.

answered Jul 29, 2022 at 20:16

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.