If I define a pointer pointing to a smart pointer, does this eliminate the advantages of smart pointer?

88 Views Asked by At

C++ smart pointer: if in a class, I define a pointer pointing to a smart pointer, does this eliminate the advantages of smart pointer? (Note, I didn't say I want to apply this kind of usage)

Like:

class TestClass
{
    public SmartPt* ptr1;
}

Here SmartPt is the smart pointer class.

Because if I do not manage the pointer well, the pointed smart pointers will not be managed too.

So does this mean it is not a good practice to use a pointer pointing to a smart pointer? So it is better to directly use the smart pointer, like:

public SmartPt object1;

[Update 1] To not distract the reader, previously I use MySmartPt, here I replace it with SmartPt.

2

There are 2 best solutions below

0
On

No, you should not try to use a pointer to a smart pointer like in the example you are sharing.

smart pointers in C++ are built around RAII principles which try to get rid of the * operator as much as possible. They also use copy/assignment overloading which raw pointers do not understand.

0
On

So if you mean doing something like this:

void * vptr;
int i = 1346;

std::shared_ptr<int> sptr = std::make_shared<int>(i);

vptr = &sptr;

Then the shared pointer will delete itself once it goes out of scope, because, that is what it is supposed to be doing. Smart pointers do not keep references of pointers to them, only references of smart pointers to their data.

Also, if you call delete vptr; one of two things will happened:

  1. The smart pointer is going to be very mad that it had delete called.
  2. If the smart pointer is out of scope then the vptr is pointing to an invalid block of memory.