I have a few containers in a class, for example, vector or map which contain shared_ptr\'s to objects living on the heap.
For example
template
If someone passes you a shared_ptr
you should never be able to modify T
. It is, of course, technically possible to cast the const T
to just a T
, but that breaks the intent of making the T
const
. So if you want people to be able to add objects to your class, they should be giving you shared_ptr
and no shared_ptr
. When you return things from your class you do not want modified, that is when you use shared_ptr
.
shared_ptr
can be automatically converted (without an explicit cast) to a shared_ptr
but not the other way around. It may help you (and you should do it anyway) to make liberal use of const
methods. When you define a class method const
, the compiler will not let you modify any of your data members or return anything except a const T
. So using these methods will help you make sure you didn't forget something, and will help users of your class understand what the intent of the method is. (Example: virtual shared_ptr
)
You are correct on your second statement, you probably do not want to instantiate your class as
, since you will never be able to modify any of your T
s.