• 您的位置我爱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  关键字:
  • () { MyClass * p(new MyClass ); p->DoSomething (); delete p; }What happens if DoSomething() throws an exception? All the lines after it will not get executed and p will never get deleted! If we´re lucky, this leads only to memory leaks. However, MyClass may free some other resources in its destructor (file handles, threads, transactions, COM references, mutexes) and so not calling it my cause severe resource locks.

    If we use a smart pointer, however, p will be cleaned up whenever it gets out of scope, whether it was during the normal path of execution or during the stack unwinding caused by throwing an exception.

    But isn´t it possible to write exception safe code with regular pointers? Sure, but it is so painful that I doubt anyone actually does this when there is an alternative. Here is what you would do in this simple case:

    void foo我对这篇文章有话说?
  • 广告位招租,广告代号:content_468_15
  • 上一篇:让应用程序从IE中获取键入的网址
    下一篇:企业上网的几个理由
  • 相关文章