将 boost::intrusive_ptr 与嵌套类一起使用
具体来说,我需要声明(据我所知) 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++ 大师们,处理这个问题的正确方法是什么?
Specifically, I need to declare (as I understand it) intrusive_ptr_{add_ref,release}
as friends of my referenced class:
#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++;
}
};
I'm having trouble finding the right syntax to make this compile and keep the access that I want. My main problem is that gcc seems to be upset that "boost::intrusive_ptr_release(Outer::Inner *p) should have been declared in namespace boost".
I see from this example that the intrusive_ptr helpers are forward declared inside of namespace boost-- but I can't forward declare them, because as I understand it, nested classes (i.e. "Inner", which these functions refer to) can only be forward-declared inside their outer classes, and that's where the friend declaration has to go too.
O greater C++ gurus, what is the proper way to handle this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您不必将它们放在
namespace boost
中,您可以将它们放在与class Outer
相同的命名空间中,并且可以通过参数相关查找找到它们。You don't have to put them in
namespace boost
, you can put them in the same namespace as yourclass Outer
and they'll be found through argument dependent lookup.