I have a class A which is storing instance of another class B. Class A does not need to have ownership of B. So it can store raw pointer/weak_ptr
instead of sharing ownership of A. End user will be using class A and B instances, class A does not exist without B. There will be multiple instances of A which needs to store same instance of A. So semantically A should be destructed before B. So I have 3 options, how to store B instance inside A.:
- Store raw pointer. This will put some restrictions on the end user that certain APIs/destruction of A should happen before B. This can be documented in class header.
- Store
weak_ptr
.weak_ptr
has some performance penalties every-time it is accessed or checked to be valid. I would prefer 1 over this. - Store
shared_ptr
. Since 1 puts restrictions on the end user for managing the life-time. this will solve the problem, howevershared_ptr
comes with the cost and sharing ownership is not required here. Class B instance will be created during initialization and used later. So maybe if it is only about init cost ofshared_ptr
, it would be better instead over 1?
I am looking for the inputs which one is best practice.
Aucun commentaire:
Enregistrer un commentaire