智能指针五大黄金法则(Five Golden rules of smart pointers)

Five Golden rules of smart pointers

Remember these five golden rules of shared pointers and everything will be ok.
Assume there are classes T and V that uses smart pointers.

  1. For objects that have a smart pointer NEVER use T*. The best way to handle this is have a private constructor and a public static Get function that returns a smart pointer. Never delete an object.
  2. Create a typedef to every smart pointer. typedef boost::shared_ptr<T> TRef;
  3. Do NOT use smart pointers to reference pointers. Smart pointers are used only to reference objects. There is NO conversion from a T* -> smart pointer. You can NOT call TRef tr=NULL, instead call TRef tr=Tref(); or tr.reset();
  4. No circular references, No two objects can reference each other using shared pointers. T can store a shared pointer to V, but if V needs a reference to T than V needs to use a WEAK pointer to T.
  5. There is no such thing as a temporary smart_ptr. Once a smart pointer is created you need to stored it somewhere. This means you cannot create a a smart pointer and pass it in a parameter to a function, you need to do this in two steps, create a smart pointer and store it in a variable, then pass the smart pointer to the function.

Every one of these rules has at least one exception, but until you understand why the rules are in place, do not break any of these rules and you can do almost anything you would ever want with smart pointers.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值