Can the following class design be modified to avoid crash. I don't want to use raw pointers in SomeClass so I make use of shared_ptr/weak_ptr, std::enable_shared_from_this and shared_from_this() constructs, but it has resulted into crash. Can anybody suggest better solution
#include <iostream>
class SomeClass;
class Base : public std::enable_shared_from_this<Base>
{
public:
int a = 0;
Base()
{
std::cout << "In Base\n";
}
~Base()
{
std::cout << "In ~Base\n";
}
};
class Derived : public Base
{
public:
int b = 0;
std::shared_ptr<SomeClass> sc;
Derived()
{
std::cout << "In Derived\n";
}
~Derived()
{
sc = nullptr;
std::cout << "In ~Derived\n";
}
void Test()
{
std::shared_ptr<Derived> b1(this);
sc = std::make_shared<SomeClass>(std::static_pointer_cast<Derived>(b1->shared_from_this()));
}
};
class SomeClass
{
public:
std::weak_ptr<Derived> derived_;
SomeClass(std::shared_ptr<Derived> derived)
{
derived_ = derived;
std::cout << "In SomeClass\n";
}
~SomeClass()
{
std::cout << "In ~SomeClass\n";
}
};
void Function()
{
Derived d;
d.Test();
}
Aucun commentaire:
Enregistrer un commentaire