mercredi 30 mars 2022

using Raw pointer vs shared_ptr and weak_ptr for non-ownership

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.:

  1. 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.
  2. 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.
  3. Store shared_ptr. Since 1 puts restrictions on the end user for managing the life-time. this will solve the problem, however shared_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 of shared_ptr, it would be better instead over 1?

I am looking for the inputs which one is best practice.

Aucun commentaire:

Enregistrer un commentaire