2

I have been using Raw pointers for a while , now i am trying to use Smart Pointers.

if ClassB is child of ClassA.

I can do this with raw pointers.

 ClassA* ptr = new ClassB;

Will this line be equivalent to the above line.

std::shared_ptr<ClassA> ptr = std::shared_ptr<ClassB>(new ClassB);

when ptr goes out of scope the memory will be cleared.

  • 5
    https://en.cppreference.com/w/cpp/memory/shared_ptr/shared_ptr , constructor 9 performs this conversion. You probably want to use `std::make_shared`, not pass a `ClassB*`. – James Picone Aug 29 '19 at 03:34

2 Answers2

2

Kinda yes.

Kinda is because std::shared_ptr is slower than raw pointers. Object won't get deallocated if you passed a copy of the shared pointer somewhere else, but it will get deallocated once all the shared pointers to it are gone.

Furthermore, the reference counter tracker is safe-thread.

Also ClassA need not have a virtual destructor for the shared pointer to work properly.

As you can imagine, these features are costly.

If you need same performance as raw pointers, you can achieve it by utilizing std::unique_ptr. Though, it is non-copyable and its usage might confuse newly introduced to C++11.

Aside from that, it is recommended to use std::make_shared and std::make_unique for initializing said smart pointers.

ALX23z
  • 4,456
  • 1
  • 11
  • 18
  • @Sam You can move one unique pointer to another, or generate a new unique pointer and copy the data. But you cannot copy. – ALX23z Aug 29 '19 at 03:46
  • 2
    @sam also you can take the raw pointer value from unique pointer obviously (otherwise you couldn't pass it to functions which take that pointer, for example). These copies of the pointer value just become dangling pointers when allocation is freed (by unique_ptr going out of scope), exactly like just using plain raw pointers (which is why you use shared_ptr when you need longer lifetime). – hyde Aug 29 '19 at 04:01
  • When using smart pointers you also need to take into a count what the types of the smart pointers imply about how they are being used. I see a `shared_ptr` and I assume that multiple objects have an ownership stake in the resource it stores. It will not be destroyed on an easily predictable schedule. If it's not used to share, I'm going to make bad decisions about how to interact with the code. If I see a `unique_ptr` I know exactly who owns it. If I get a reference to one I know I don't have to worry about it. Someone else has that job. With a raw pointer you know nothing about the ownership. – user4581301 Aug 29 '19 at 05:17
  • Handy reading: [What is ownership of resources or pointers?](https://stackoverflow.com/questions/49024982/what-is-ownership-of-resources-or-pointers) – user4581301 Aug 29 '19 at 05:18
0

Did you try it in code ?

I think you could have simply done std::shared_ptr<ClassA> ptr(new ClassB) directly.

phuclv
  • 37,963
  • 15
  • 156
  • 475
user3389943
  • 147
  • 1
  • 7