智能指針五大黃金法則(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.

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章