【发布时间】:2020-03-15 23:05:38
【问题描述】:
我正在使用无法解决这种循环依赖的代码库:
foo.h
class Foo
{
public:
using Ptr = std::shared_ptr<Foo>;
using ConstPtr = std::shared_ptr<const Foo>;
void setter(const Bar::Ptr& bar_ptr) {};
private:
Bar::WeakPtr bar_ptr_;
};
和
bar.h
class Bar
{
public:
using Ptr = std::shared_ptr<Bar>;
using ConstPtr = std::shared_ptr<const Bar>;
using WeakPtr = std::weak_ptr<Bar>;
Bar(Foo::ConstPtr foo_ptr) : foo_ptr_(std::move(foo_ptr)) {};
private:
Foo::ConstPtr foo_ptr_;
};
它之前正在编译,因为有一个外部标头,其中:
using FooPtr = std::shared_ptr<Foo>;
using FooConstPtr = std::shared_ptr<const Foo>;
using BarPtr = std::shared_ptr<Bar>;
但由于追求一致性,我想要Foo::Ptr、Foo::ConstPtr、Bar::Ptr。我有机会得到它吗?
编辑:添加了Bar::WeakPtr,因为我认为我已经遇到了麻烦,所以之前缺少它。
【问题讨论】:
-
您能解释一下
using的要求并且不使用变量吗? -
@cigien:不,这些不是嵌套的
-
@jackw11111
using是为了隐藏它是std::shared_ptr而不是boost::shared_ptr的事实,有时很快。其实是using Ptr = my_namespace::shared_ptr<Foo>; -
Foo没有setter()分配给的Bar::Ptr成员,实际上setter()根本不参与Bar的共享所有权,所以它应该'根本不会使用shared_ptr<Bar>(herbsutter.com/2013/06/05/…),因此您可以通过将Foo::setter()更改为void setter(const Bar* bar_ptr)来打破循环依赖关系,然后转发声明Bar -
@RemyLebeau 你几乎是对的,我刚刚检查了
Foo有一个Bar::WeakPtr。我把例子简化了太多,让我修复它。
标签: c++ using circular-dependency forward-declaration