ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

c – 这里发生了什么?

2019-07-29 21:06:15  阅读:92  来源: 互联网

标签:c smart-pointers boost-smart-ptr


这不编译,

#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().

标签:c,smart-pointers,boost-smart-ptr
来源: https://codeday.me/bug/20190729/1575209.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有