Search code examples
c++unique-ptrderived-class

Passing unique_ptr with derived class causes SEGFAULT


could someone explain to me why executing function foo() here causes SEGFAULT? When I change the unique_ptr object in D class to contain B class object instead of A, everything works ok.

class A
{
    public:
    virtual void function() = 0;
};

class B : public A
{
    public:
    void function()
    {
        std::cout << "works!!";
    }
};

class D
{
    public:
    D(const std::unique_ptr<A>& arg): object(arg) {}

    void foo()
    {
        object->function();
    }

    private:
    const std::unique_ptr<A>& object;
};


int main()
{
    std::unique_ptr<B> object = std::make_unique<B>();
    D d(std::move(object));

    d.foo();
}

I'm curious what's the logic behind it.


Solution

  • You pass a reference to the smart pointer object. This smart pointer object will be destructed as soon ad the d object have been created. That leaves you with an invalid reference. When you try to use it, you will have undefined behavior.

    Instead pass the pointer object by value, store it by value in the object, and move it into the object:

    class D
    {
    public:
        D(std::unique_ptr<A> arg): object(std::move(arg)) {}
    
        // ...
    
        std::unique_ptr<A> object;
    };