智能指针五大黄金法则(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.

你可能感兴趣的:(智能指针五大黄金法则(Five Golden rules of smart pointers))