我想使用共享指针创建两个相互指向的类。但是,我编写的代码会导致崩溃并带有 Access Violation 错误代码。我已经使用原始指针重写了代码,它完美无缺,但我想尝试使用共享指针。
问题:我可以更改下面的代码以解决崩溃的同时仍然使用共享指针吗?
struct B;
struct A
{
void create();
std::shared_ptr<B> b = 0;
};
struct B
{
B(std::shared_ptr<A>&& a) : a(a) {}
std::shared_ptr<A> a;
};
void A::create()
{
b = std::make_shared<B>(std::shared_ptr<A>(this));
}
int main()
{
std::shared_ptr<A> obj;
obj->create();
}