C++ smart pointer const correctness

后端 未结 5 1158
你的背包
你的背包 2020-12-24 10:56

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 

        
5条回答
  •  时光说笑
    2020-12-24 11:32

    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 myGetSharedPtr(int index) const;)

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

提交回复
热议问题