Edit: the confusion was that you're not trying to reference count the program
class, but to reference count copies of name_
with the same value.
Given this, it seems cleaner to create something with similar semantics to shared_ptr
, but for value types ... let's call it shared_value
:
template <typename T, void (*Deleter)(T)>
struct shared_value {
typedef shared_value<T,Deleter> Self;
// whatever ctors, assignment operators etc. you need here:
shared_value(Self const &other)
: value_(other.value_), refs_(other.refs_) {
++*refs_;
}
~shared_value() {
if (resf_) {
if (*refs_ == 1) {
Deleter(value_);
delete refs_;
}
else
--*refs_;
}
}
operator T& () { return value_; }
operator T const& () const { return value_; }
private:
T value_;
mutable int *refs_;
};
and use it like:
class program {
shared_value<GLuint, glDeleteProgram> name_;
};
You can add flexibility with a polymorphic deleter here - I've just shown the simplest thing that should work for you.
There's an easy way to do what you want, without using CRTP or mixins or touching the program class at all. Simply write it like this:
class program {
GLuint name_;
public:
~program() {
glDeleteProgram(name_);
}
};
and then use std::shared_ptr<program>
everywhere you currently use program
(that is, only create one instance and then pass around shared pointers to it).
If you don't have std::shared_ptr
yet, use boost::shared_ptr
instead.