Search code examples
c++shared-ptrdynamic-cast

shared_ptr std::dynamic_pointer_cast fails with "attempting to reference a deleted function" error


I have seen all the posts in StackOverflow regarding this similar error and still couldn't find what is causing issue in mine.

I'm using std::dynamic_pointer_cast to cast a std::shared_ptr<Base> object to a std::shared_ptr<DerivedShared> object, but I'm encountering a "attempting to reference a deleted function" error. I've ensured that the Base destructor is virtual but the error persists.

What could be causing this error, and how can I resolve it? Are there any known limitations or bugs in the standard library that could be contributing to this issue? Any insights or suggestions would be greatly appreciated.

P.S : I know it works with static_pointer_cast but wondering what is causing issue with dynamic_pointer_cast!

struct Base
{
    Base() = default;
    virtual ~Base() = default;
    //Copy
    Base(const Base&) = default;
    Base& operator=(const Base&) = default;
    //Move
    Base(Base&&) = default;
    Base& operator=(Base&&) = default;
};


struct DerivedShared : public  Base
{
public:
    DerivedShared() //: data(std::shared_ptr<int[]>(new int[3]{1,2,3}))
    {
        //data = std::make_shared<int[]>(new int[3]{ 1,2,3 });
        data = std::shared_ptr<int[]>(new int[3]{ 1,2,3 });
    }
    
public:
    std::shared_ptr<int[]> data;
};

int main()
{
    std::cout << "----------------------------------------\n";
    std::shared_ptr<Base> base5 = std::make_shared<DerivedShared>();
    for (size_t i = 0; i < 3; ++i)
    {
        std::cout << std::dynamic_pointer_cast<DerivedShared>(base5)->data[i] << '\n';
    }
}

Solution

  • You disabled RTTI and in this case Microsoft's implementation of the standard library defines std::dynamic_pointer_cast as deleted, since the dynamic_cast can't work without RTTI. (See https://github.com/microsoft/STL/blob/main/stl/inc/memory#L2049.)

    You can't disable RTTI if you want to use std::dynamic_pointer_cast.