If I need polymorphism, should I use raw pointers instead of unique_ptr?

If I need polymorphism, should I use raw pointers instead unique_ptr?

I saw several threads that show how to use unique_ptrfor polymorphic behavior. I'm not sure if it's worth it; I would rather stay with raw pointers. Can you comment on this, your opinion on raw and smart pointers in this context?

+7
source share
3 answers

The following simple code shows that std::unique_ptrit works great in terms of polymorphism by typing "Hello from Derived.",

#include <iostream>
#include <memory>
using std::cout;

struct Base 
{
    virtual ~Base() { }

    virtual void SayHello()
    {
        cout << "Hello from Base.\n";
    }
};

struct Derived : public Base
{
    void SayHello() override
    {
        cout << "Hello from Derived.\n";
    }
};

int main()
{
    std::unique_ptr<Base> pBase( new Derived() );    
    pBase->SayHello();
}

In any case, observing raw pointers is fine; what you should pay attention to is the presence of raw pointers. Owners of raw pointers should be safely wrapped in RAII boundaries (using unique_ptr, shared_ptror some kind of user resource manager).

+10
source

Smart pointers relate to ownership / life. Where you need to control the lifetime of a polymorphic object, use the smart pointer. If you just use an object, prefer raw links / pointers (in that order) over smart pointers.

+1
  • unique_ptr , . unique_ptr.

  • , . a unique_ptr , .

  • , . .

+1

Source: https://habr.com/ru/post/1529488/


All Articles