使用boost::intrusive_ptr与嵌套类

Using boost::intrusive_ptr with a nested classes

本文关键字:嵌套 ptr boost intrusive 使用      更新时间:2023-10-16

具体来说,我需要声明(根据我的理解)intrusive_ptr_{add_ref,release}为我引用的类的朋友:

#include <boost/intrusive_ptr.hpp>
using boost::intrusive_ptr;
class Outer {
public:
    //user-exposed interface goes here
protected:
    class Inner {
    public:
        Inner():refct(0){}
        virtual ~Inner(){}
        //machinery goes here
        size_t refct;
    };
    friend void boost::intrusive_ptr_release(Inner *p);
    friend void boost::intrusive_ptr_add_ref(Inner *p);
    intrusive_ptr<Inner> handle;
};
namespace boost {
    void intrusive_ptr_release(Outer::Inner *p){
        if ((p->refct -= 1) <= 0){
            delete p;
        }
    }
    void intrusive_ptr_add_ref(Outer::Inner *p){
        p->refct++;
    }
};

我在找到正确的语法来进行编译并保持我想要的访问时遇到了麻烦。我的主要问题是gcc似乎对"boost::intrusive_ptr_release(Outer::Inner *p)应该在命名空间boost中声明"感到不安。

我从这个例子中看到,intrusive_ptr帮助器是在命名空间boost内部向前声明的——但是我不能向前声明它们,因为在我的理解中,嵌套类(即:"内部"(这些函数所引用的)只能在它们的外部类中向前声明,这也是友元声明必须要去的地方。

C++大师们,什么是正确的方法来处理这个?

您不必将它们放在namespace boost中,您可以将它们放在与class Outer相同的命名空间中,它们将通过参数依赖查找找到。

每个新的intrusive_ptr实例使用不限定的调用intrusive_ptr_add_ref函数,并将指针作为参数传递给它,从而增加引用计数。