-2
unique_ptr<X> f()
{
    unique_ptr<X> p(new X);     // or {new X} but not = new X
    // do something - maybe throw an exception
    return p;   // the ownership is transferred out of f()
}

When the exception throw-ed, why we care about the existence of Object X, why we care about the memory it occupied?

The process will terminated soon after the handling of the exception, and the memory will be released, why we care about this?

  • 2
    Because sometimes people actually care about guaranteeing the quality of their programs, instead of making excuses. :) And how do *you* know what's going to happen during an exception? Only the catcher knows that. Maybe I catch it, log it, and continue down an alternate path. Or maybe not. Why guess? – GManNickG Aug 08 '12 at 01:40
  • @GManNickG If I don't use exception at all in my software, does that means that I don't need the smartpointer and RAII? –  Aug 09 '12 at 02:04
  • 2
    If by not using exceptions you mean they are disabled at a language-level by the compiler (that is, you are not using C++ but C++-without-exceptions), then that's partially correct. RAII is still useful for automating memory usage and modeling transations (compare how easy it is to have a reference count with and without `shared_ptr`). If you mean *you* don't use exceptions, but they are still enable, then you're still just using exceptions. `new int` can throw, for example. – GManNickG Aug 09 '12 at 02:07

2 Answers2

6

Because in most applications, the process won't be terminated immediately, and you don't want to leak memory. You might as well ask why you should care about memory leaks at all.

Antimony
  • 37,781
  • 10
  • 100
  • 107
  • Memory leaks may exist in application that will terminated by the leak. But with exception, the application is destined to die soon or later. –  Aug 08 '12 at 01:40
  • 4
    @upton, some exceptions can be handled in a way that allows the program to run for a long time afterwards. If your programs always stop immediately after an exception then you are free to ignore the conventional advice - but just hope that the people who inherit your code are not psycopaths. – Mark Ransom Aug 08 '12 at 01:46
6

The process will terminated soon after the handling of the exception

Says who?

If all you will do in the presence of an exception is terminate, then yeah, you can ignore it. However, there are plenty of exceptions that you should catch. Making your code relatively bullet-proof to exceptional circumstances is not a bad thing.

And once you decide to actually start trying to catch exceptions rather than ignoring them, you need RAII.

Nicol Bolas
  • 449,505
  • 63
  • 781
  • 982