Let's assume the following scenario. I have an implicitly shared class as defined below:
class MyClass
{
public:
MyClass (void) {
data = new Data();
data->refs = 1;
data->dummy = 32;
}
~MyClass (void) {
if (--data->refs == 0)
delete data;
}
MyClass (const MyClass& c) {
++(data = c.data)->refs;
}
MyClass& operator = (const MyClass& c) {
++(data = c.data)->refs;
return *this;
}
private:
struct Data {
int refs;
int dummy;
} *data;
};
The idea is that when this class gets copied, the internal pointer to the data gets copied and the number of references to that data is incremented. However, consider the following:
int main (void)
{
MyClass c1;
c1 = MyClass();
c1 = MyClass();
return 0;
}
My understanding is that there are three instances of MyClass and only the last instance gets deallocated. If this is the case, what can I do to avoid these scenarios and ensure that every instance of MyClass gets cleaned up?