2013年10月13日 星期日

CxxlMan 程式庫注意事項--不要在建構函數中將 this 放入 Smart_Ptr

如下:
A::A()
{
  Smart_Ptr(this);
}
這樣從建構函數返回後,A 的物件也會被銷毀,最常發生的情況應如下:
void F(const Smart_Ptr<A> &A_Arg); // 假設沒有用 Smart_Ptr 保存 A
A::A()
{
  F(this);
}
常不自覺就犯下那樣的錯誤。


另外 new 出來的 A 若沒放入 Smart_Ptr 就呼叫 F(),也是會從 F() 返回後就被銷毀,為了避免這種情況,class A 的寫法應如下比較好:

class A:public cxxlObject
{
private:
/*
  // 不希望被繼承,建構函數可以放這
  A()
  :cxxlObject(Spirit_Easy)
  {}
*/

  ~A(){}
protected:
  // 不希望被直接 new
  A()
  :cxxlObject(Spirit_Easy)
  {}
public:

  // 強迫使用 Smart_Ptr
  static Smart_Ptr<A> cxxlFASTCALL Create()
  {
    return new A();
  }
};






沒有留言:

張貼留言