New ones never fail?

In C ++, we usually see and write code, for example,

Sample sample=new Sample();
if ( sample == NULL )
{
     std::cout<<"Memory allocation failed" << std::endl;
}

But in C #, I rarely see this: (at least I never saw this)

Sample sample = new Sample();
if ( sample == null )
{
     Console.WriteLine("Memory allocation failed\n");
}

So in C # we rarely check if a newfails or not. Why is this so? Is this related to "In C #, the new will never work"? Is there such a thing in C # that newnever fails?

If this fails, then why is such a “check” so rare in C #? I am not talking about OutOfMemoryException, that is, after all exceptions, not "check". I am talking about coding style.

+3
source share
10 answers

According to msdn

, OutOfMemoryException.

http://msdn.microsoft.com/en-us/library/51y09td4%28v=vs.71%29.aspx

, ++ 0 . std:: bad_alloc . - ,

Sample sample=new(std::nothrow) Sample();
+14

#, new OutOfMemoryException, , NULL .

, ++ - new throws std::bad_alloc, , NULL ++.

+12

++, malloc, new NULL . , std::bad_alloc .

, new NULL , , . std::nothrow . ( : <new>)

+6

new , OutOfMemoryException.

, ++, , :

try { 
  Sample sample = new Sample();
} catch(OutOfMemoryException e) {
  Console.WriteLine("Memory allocation failed\n");
}
+5
Sample sample=new Sample();
if ( sample == NULL )
{
     // You will never get here!
     std::cout<<"Memory allocation failed" << std::endl;
}

++. "Memory allocation failed" . , . ++ std::bad_alloc, # it OutOfMemoryException.

+5

, , .

. .

+1

# OutOfMemoryException

+1
  • ++
  • #, Exception
+1

++ new NULL (. NULL ?)

++ , new , , #.

NULL .

+1

- , ? , , , , .

However, you can, of course, run out of memory if you allocate sufficient memory and save references to it (at this point, an exception will be thrown - the NULL pointer as the return value for memory allocation is more common in C, and in versions in C + + written for video game consoles.)

0
source

Source: https://habr.com/ru/post/1787096/


All Articles