This is how my company implements reference counting objects in C++:
#ifndef DECLARE_REF_COUNT
#define DECLARE_REF_COUNT \
public: \
void Ref() { atomic_inc(_refs); } \
void UnRef() { \
int n = atomic_dec(_refs); \
if (n <= 0) { \
delete this; \
} \
} \
private: \
volatile int _refs;
#endif
So when you need to create a reference counting class, you do:
class MyClass {
DECLARE_REF_COUNT;
public:
...
};
When you use it, you do:
myobj->Ref();
...
myobj->UnRef();
I have proposed using shared pointer to my leader, as it doesn't need to Ref and UnRef manually, but my leader prefers the Macro way and he told me that we won't forget to call UnRef() because it's so basic and we don't hire those who will forget to do this. Another reason he prefers using Macro is because it give more control when some explicit Ref and UnRef is needed. So suppose no boost and no c++11, is Macro a good way to do so? And what's the advantage and disadvantage of this way?