trbabb
trbabb

Reputation: 2095

Using boost::intrusive_ptr with a nested classes

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?

Upvotes: 4

Views: 994

Answers (1)

Yakov Galka
Yakov Galka

Reputation: 72519

You don't have to put them in namespace boost, you can put them in the same namespace as your class Outer and they'll be found through argument dependent lookup.

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.

Upvotes: 5

Related Questions