2

When I try to run this code I get bad_weak_ptr exception:

using namespace std; 

class O {
    public:
        O() {}
};
  
class A : public std::enable_shared_from_this<A>, virtual public O {
    public: 
        A() {}
};

class B : public std::enable_shared_from_this<B>, virtual public O {
    public: 
        B() {}
        void GetShared() { 
            shared_from_this();
        }   
};

class C : public A, public B {
public:
    C()  {}
};
  
int main() 
{ 
    std::shared_ptr<B> pt = std::make_shared<C>();
    pt->GetShared();
}

I would like to create instance of C class but then return B shared_ptr because that is what other interface requires. Is there a way to fix this code ? I cannot seem to do that.

1 Answers1

0

Well as far as I know you are trying to do the undoable:

Inheritance in C++ means that you also include the same members of the parent classes. However for class C that would mean 2 classes that are already supposed to be held by a std::shared_ptr. But by the inheritance you tell the compiler that C should contain sub instances of A and B not held by a std::shared_ptr. shared_from_this will complain about this fact at run time by a bad weak ptr exception.

Probably you want C to be held only by a std::shared_ptr, then you can to the attached code.

If you simply want to "up-cast" a instance of C i.e. use it as it would be a class of B you can simply use a B& or use std::shared_ptr with out std::enables_shared_from_this or only on the up most class.

#include <memory>

using namespace std;

class O {
public:
    O() {}
};

struct A : virtual public O {
};

struct B : virtual O {
    B() {}
    void GetShared() {
    }
};

struct C : std::enable_shared_from_this<C>, A, B {
    C() = default;
};

int main()
{
    std::shared_ptr<B> pt = std::make_shared<C>();
    pt->GetShared();
}
Superlokkus
  • 4,731
  • 1
  • 25
  • 57