I'm trying to allow a class to contain a pointer, which may either be an owned pointer or a borrowed pointer. In the former case, it should destroy the owned object itself; in the latter case, it shouldn't destroy the pointed-to object.
In code, I have classes A, B and C. I'm aiming for the following (simplified) definitions, where B is the class that needs to own a pointer:
class C {
...
};
class B {
C *c;
B(C *c) : c(c) {
}
};
class A {
C c1;
B b1, b2;
// b2 leaks pointer to C
A() : b1(&c1), b2(new C()) {
}
};
When an instance of A
destructs, it destroys c1
, b1
and b2
. Ideally, the destruction of b2
should delete the anonymous C
instance, but the destruction of b1
should not delete anything (since c1
will be destroyed by A directly).
What kind of smart pointer can I use to achieve this? Or, is the best solution just to pass an ownership flag to B?