I want to use boost::intrusive_ptr for refcounting my class x::Y, so I add a references field and friend declarations for the release and add_ref functions, which should be defined in namespace boost. Then, I write those functions. Like this:
namespace x{
class Y{
long references;
friend void boost::intrusive_ptr_add_ref(x::Y * p);
friend void boost::intrusive_ptr_release(x::Y * p);
};
}
namespace boost
{
void intrusive_ptr_add_ref(x::Y * p)
{
++(p->references);
}
void intrusive_ptr_release(x::Y * p)
{
if (--(p->references) == 0)
delete p;
}
}
The code does not compile, I receive the following errors:
test/test6.cpp:8:18: error: ‘boost’ has not been declared
test/test6.cpp:9:18: error: ‘boost’ has not been declared
test/test6.cpp: In function ‘void boost::intrusive_ptr_add_ref(x::Y*)’:
test/test6.cpp:7:11: error: ‘long int x::Y::references’ is private
test/test6.cpp:17:9: error: within this context
test/test6.cpp: In function ‘void boost::intrusive_ptr_release(x::Y*)’:
test/test6.cpp:7:11: error: ‘long int x::Y::references’ is private
test/test6.cpp:22:13: error: within this context
I thought I did everthing like explained by the boost documentation, but it seems that I did something wrong. Where is the problem?
The errors are because you are referring to the
boostnamespace in your class definition, before any declaration of that namespace. You can fix it by declaringnamespace boostbefore your class definition; you’ll also need to declare the functions, and to do that you’ll also need to declare the class and namespace:However, if might be better to put the functions not in the
boostnamespace, but in the namespace containing your class (i.e. innamespace x). Thenintrusive_ptrwill find the correct version by argument-dependent name lookup. This doesn’t require any declarations before the class.