c++ - Pointer class member and deleting responsibilities -
if class has pointer of sort can set class clients, how should deal deletion?
example:
class { }; class b { public: void seta(a* a) { this->a = a; } private: a* a; };
how should destructor of class b
? should delete a
? see, there 2 way user can set pointer:
... // assume b object b being created elsewhere aobj; a* aptr = new a(); b.seta(&aobj); // not ok use delete, , class member // point invalid memory location once aobj goes out // of scope b.seta(aptr); // using new make pointer available after // block of code ...
so right way of deleting b? should perform new
in set
method?
how should destructor of class b? should delete a?
you, author of class, decides of semantics. don't think in terms of pointers, references, , delete
s. think in terms of design: what's relation between a
, b
? b
needs a
for?
two common types of relation delegation , composition. delegation mean client code uses seta
member have instance aware of other b
instance may use further uses. composition mean seta
member used initialize internal part of instance.
one possible implementation of delegation using member pointer. i'd recommend passing reference seta
assign pointer; sidesteps issue of checking 0
, makes obvious client code there no ownership issue deal with. compatible polymorphic types.
one possible implementation of composition using a
member, , passing reference const or value assign it. use smart pointer, if a
meant used polymorphically. passing smart pointer simplest thing -- you'll have check 0
and/or document cast.
no matter decide use (which doesn't have in list anyway), use code tool achieve purpose or design. don't let code dictate thoughts.
in example implementations don't have special in destructor.
Comments
Post a Comment