加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 这里发生了什么?

发布时间:2020-12-16 09:39:34 所属栏目:百科 来源:网络整理
导读:这不编译, #include boost/intrusive_ptr.hppclass X{public: void intrusive_ptr_add_ref(X* blah) { }void intrusive_ptr_release(X * blah){}};int main(){ boost::intrusive_ptrX ex(new X);} 但这样做: #include boost/intrusive_ptr.hppclass X{publi
这不编译,

#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有关(我还没有想过要理解)? friend限定符是否将已定义的函数作为自由函数放在封闭的命名空间中?

编辑

谁删除了他们的帖子,成员函数非朋友作为add_ref和release(documention中没有提到这些特定的成员函数……)确实解决了问题.使用好友限定符的嵌套定义会发生什么?

解决方法

从boost :: intrusive_ptr的文档:

Every new intrusive_ptr instance increments the reference count by using an unqualified call to the function intrusive_ptr_add_ref,passing it the pointer as an argument. Similarly,when an intrusive_ptr is destroyed,it calls intrusive_ptr_release; this function is responsible for destroying the object when its reference count drops to zero. The user is expected to provide suitable definitions of these two functions. On compilers that support argument-dependent lookup,intrusive_ptr_add_ref and intrusive_ptr_release should be defined in the namespace that corresponds to their parameter; otherwise,the definitions need to go in namespace boost.

这意味着intrusive_ptr_add_ref和intrusive_ptr_release不应该是成员函数,而是自由函数(友元函数就像这样).此外,它们在没有限定条件的情况下被调用,因此它们应该位于全局命名空间或ADL找到的某个位置.

编辑:关于使用朋友限定符的嵌套定义的问题:友元函数被定义为非成员函数,因此朋友void intrusive_ptr_add_ref(X * blah)将被称为intrusive_ptr_add_ref(my_x_ptr)而不是my_x_ptr-> intrusive_ptr_add_ref().

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读