jeudi 26 décembre 2019

When should we use std::unique_ptr vs std::shared_ptr for class memeber variables?

I know the general philosophy behind std::unique_ptr<T> and std::shared_ptr<T>. A unique pointer should be used in cases where no other pointer variable will ask for access to the object / primitive data pointed to by the unique pointer. A shared pointer, however, exists for shared/concurrent access to a single resource such as a file.

This all remains true for class data members of pointer types as well of course. However, in particular regards at the implementation level, does this general rule cover all cases?

  • Assume that you have a class with 3 member variables, all of pointer type. If none of your member functions return a pointer to one of these variables (such as a getter function) then you should declare the member variable to be of type std::unique_ptr<T>. If however, you return one these member variables then you could potentially have a situation where another pointer tries to bind to the same resource. In which case, you should declare that particular member to be of type std::shared_ptr<T>.

This seems to be a logical rule to follow. I guess, what I'm trying to figure out is how to deal with smart pointers when declared as member variables because the decision is more difficult.

Aucun commentaire:

Enregistrer un commentaire