c++ - New (std::nothrow) vs. New within a try/catch block -


Contrary to malloc () ,

I did some research after learning new < / Code> which I used to do, does not return zero for the failed allocation, and it has been found that whether the new has been successful or not, there are two different ways to check it. These are two ways:

  try {ptr = new int [1024]; } Hold (std :: bad_alloc & exc) {assert (); };   

and

  ptr = new (std :: nothrow) int [1024]; (PTR == faucet) by emphasizing ();   

I believe that two methods meet the same goal, (correct me if I am definitely wrong!), So my question is:

Which is better than checking the D-Facto C ++ programming conferencing, if the new is successful, then it is based entirely on readability, maintenance and performance. the option.

Consider what you are doing If you are allocating the memory and if for some reason the memory If the allocation can not work, then you emphasize which is more or less OK, if you only broadcast std :: bad_alloc back to main What will happen if you do? In a release build, where insert is a no-op, your program crashes when it tries to access memory, then this exception is similar to telling the bubble: preventing the app .

Then ask yourself a question: Do you need to take care of in fact if you are out of memory? If you are pushing what you are doing, then the exception method is better, because it does not clutter your code with the random assert s. You just leave the exception to the main Come back on.

If you actually do special codepages in this event, you can not allocate memory (that is, you can actually continue the function), the exception can be any kind or not , It can be what the codepath is. If the codepath is set to a switch with just one signal set, then the nothrow version will be simpler if instead, you need to do something different (drag with a steady buffer, or remove some stuff, or whatever ), Then holding std :: bad_alloc is good enough.

Comments

Popular posts from this blog

mysql - BLOB/TEXT column 'value' used in key specification without a key length -

c# - Using Vici cool Storage with monodroid -

c# - Confused over DLL entry points (entry point not found exception) -