• 您的位置我爱Aspx >> VC.Net >> Don Box:Smart Pointers : What , Why , Which?
  • Don Box:Smart Pointers : What , Why , Which?

  • 作者:aspxer  来源:internet  日期:2007-5-21 23:48:24  关键字:
  • * p(new MyClass ); MyClass * q = p; delete p; p->DoSomething (); // Watch out! p is now dangling! p = NULL; // p is no longer dangling q->DoSomething (); // Ouch! q is still dangling!For auto_ptr, this is solved by setting its pointer to NULL when it is copied:
    template <class T> auto_ptr <T>& auto_ptr <T>::operator= (auto_ptr <T>& rhs) { if (this != &rhs) { delete ptr; ptr = rhs.ptr; rhs.ptr = NULL; } return *this; }
    Other smart pointers may do other things when they are copied. Here are some possible strategies for handling the statement q = p, where p and q are smart pointers:
  • 相关文章