【问题标题】:Using boost::intrusive_ptr with a nested classes将 boost::intrusive_ptr 与嵌套类一起使用
【发布时间】:2011-08-16 06:43:45
【问题描述】:

具体来说,我需要声明(据我所知)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 中声明 boost::intrusive_ptr_release(Outer::Inner *p) ”感到不安。

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

各位 C++ 大师们,处理这个问题的正确方法是什么?

【问题讨论】:

    标签: c++ boost namespaces smart-pointers nested-class


    【解决方案1】:

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

    每个新的 intrusive_ptr 实例都会通过对函数 intrusive_ptr_add_ref 的非限定调用来增加引用计数,并将指针作为参数传递给它。

    【讨论】:

    • 你是对的;确实有效。我正在阅读的文档之一明确表示友元函数必须位于 boost 命名空间中(我链接到的示例支持该命名空间),所以我认为这是理所当然的。不知道为什么我没有早点尝试。谢谢!
    • 这里的关键字是“argumentdependent lookup”(通常称为 Koenig 的查找或简称 ADL)。 google一下吧,值得了解为什么C++中存在这样的功能以及它是如何工作的。
    猜你喜欢
    • 1970-01-01
    • 2012-12-02
    • 1970-01-01
    • 2011-09-18
    • 1970-01-01
    • 2012-12-08
    • 2017-12-27
    • 2017-01-24
    • 2017-02-28
    相关资源
    最近更新 更多