3

这不编译,

#include <boost/intrusive_ptr.hpp>

class X
{
public:
 void intrusive_ptr_add_ref(X* blah)
 {
 }

void intrusive_ptr_release(X * blah)
{
}

};



int main()
{
  boost::intrusive_ptr<X> ex(new X);
}

但这确实:

#include <boost/intrusive_ptr.hpp>

class X
{
public:
  friend void intrusive_ptr_add_ref(X* blah)
  {
  }

  friend void intrusive_ptr_release(X * blah)
  {
  }

};



int main()
{
  boost::intrusive_ptr<X> ex(new X);
}

还有这个 :

    #include <boost/intrusive_ptr.hpp>

    class X
    {
    public:


    };


    void intrusive_ptr_add_ref(X* blah)
      {
      }

      void intrusive_ptr_release(X * blah)
      {
      }

int main()
{
  boost::intrusive_ptr<X> ex(new X);
}

我想这与 SFINAE 有关(我还没有费心去理解)?朋友限定符是否将定义的函数作为自由函数放在封闭的命名空间中?

编辑

谁删除了他们的帖子,成员函数 non-friend asadd_ref和(文档release中没有提到这些特定的成员函数......)确实解决了这个问题。带有限定符的嵌套定义会发生什么?friend

4

1 回答 1

7

从以下文档boost::intrusive_ptr

每个新的 intrusive_ptr 实例都会通过对函数 intrusive_ptr_add_ref 的非限定调用来增加引用计数,并将指针作为参数传递给它。同样,当一个 intrusive_ptr 被销毁时,它会调用 intrusive_ptr_release;此函数负责在对象的引用计数降至零时销毁该对象。期望用户提供这两个函数的适当定义。在支持参数依赖查找的编译器上,应在与其参数对应的命名空间中定义 intrusive_ptr_add_ref 和 intrusive_ptr_release;否则,定义需要进入命名空间提升。

This means that intrusive_ptr_add_ref and intrusive_ptr_release should not be member functions, but free functions (friend functions behave as such). Furthermore they are called without qualification, so they should be in the global namespace or somewhere found by ADL.

Edit: To your question about nested definitions with friend qualifier: friend functions are defined as non memberfunctions, so friend void intrusive_ptr_add_ref(X* blah) will be called as intrusive_ptr_add_ref(my_x_ptr) instead of as my_x_ptr->intrusive_ptr_add_ref().

于 2012-01-06T17:35:46.203 回答