如果A
实际上并没有保留shared_ptr<B>
您传递的副本(只是B
简单地使用),那么您可以进行这项工作(见下文),但是:
- 如果
A
不保留对 the 的引用,B
则它可能只需要一个B&
orB*
参数,而不是 a shared_ptr<B>
,因此您应该更改设计。
- 如果
A
确实保留了引用,那么您将获得循环引用,因此您应该更改设计。
这行得通,但确实非常可怕,并且很容易引入错误,而且通常是一个坏主意,我可能什至不应该展示它,只需更改您的设计以避免循环依赖:
#include <memory>
#include <iostream>
class B;
class A
{
public:
A(std::shared_ptr<B> b);
};
class B : public std::enable_shared_from_this<B>
{
// return a shared_ptr<B> that owns `this` but with a
// null deleter. This does not share ownership with
// the result of shared_from_this(), but is usable
// in the B::B constructor.
std::shared_ptr<B> non_owning_shared_from_this()
{
struct null_deleter {
void operator()(void*) const { }
};
return std::shared_ptr<B>(this, null_deleter());
}
public:
B(int id)
: m_id(id), a(std::make_shared<A>(non_owning_shared_from_this()))
{ }
int id() const { return m_id; }
private:
int m_id;
const std::shared_ptr<A> a;
};
A::A(std::shared_ptr<B> b)
{
std::cout << b->id() << std::endl;
}
int main()
{
auto b = std::make_shared<B>(42);
}