home bbs files messages ]

Forums before death by AOL, social media and spammers... "We can't have nice things"

   comp.lang.c++.moderated      Moderated discussion of C++ superhackery      33,346 messages   

[   << oldest   |   < older   |   list   |   newer >   |   newest >>   ]

   Message 33,117 of 33,346   
   =?ISO-8859-1?Q?=D6=F6_Tiib?= to alan_mc...@this.is.invalid   
   Re: Null pointer from "new" operator.   
   01 Jul 13 23:15:03   
   
   From: ootiib@hot.ee   
      
   On Tuesday, 2 July 2013 00:47:31 UTC+3, alan_mc...@this.is.invalid  wrote:   
   > I keep seeing code of the form   
   > (names withheld to protect the guilty :-)):   
   >   
   >      T *t = new T( arg1, ... );   
   >      if ( t )   
   >      {   
   >         // code that uses t   
   >      }   
   >   
   > My understanding was that "new" (in contrast to malloc())   
   > never returns a null pointer; if it can't allocate the   
   > memory (or if the constructor fails), an exception is   
   > thrown.   
      
   Yes, that if has been redundant for some time but possible   
   overloading made it dim it throws or not. In C++11 it is clear.   
   Their code should look like that in C++11 to have point:   
      
          T *t = new (std::nothrow) T( arg1, ... );   
          if ( t )   
          {   
             // code that uses t   
          }   
      
   > So can I tell people who write code like this that the   
   > "if" is redundant?  Or are there obscure cases where   
   > "new" might return a null  pointer?   
      
   Unless it is a code base that is still maintained using MSVC 5.0   
   (that did not throw bad_alloc) you should certainly point it out.   
      
   > (Note: class T does not override any flavor of operator new.   
   > Also, this is not C++77 or something.)   
      
   When you override non-throwing new for T then you are expected to   
   write it in C++11 like that:   
      
          class T   
          {   
          public:   
              static void * operator new (size_t size, std::nothrow_t)   
   throw ();   
          };   
      
      
   --   
         [ See http://www.gotw.ca/resources/clcm.htm for info about ]   
         [ comp.lang.c++.moderated.    First time posters: Do this! ]   
      
   --- SoupGate-Win32 v1.05   
    * Origin: you cannot sedate... all the things you hate (1:229/2)   

[   << oldest   |   < older   |   list   |   newer >   |   newest >>   ]


(c) 1994,  bbs@darkrealms.ca