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 32,545 of 33,346   
   Seungbeom Kim to Edward Rosten   
   Re: Exception in Constructor   
   18 Sep 12 11:44:23   
   
   From: musiphil@bawi.org   
      
   On 2012-09-18 06:21, Edward Rosten wrote:   
   >   
   > struct Mem{   
   >     char* const data;   
   >   
   >      Mem(size_t s)   
   >      :data(new (nothrow) char[s])   
   >      {   
   >          if(!data)   
   >            throw bad_alloc();   
   >      }   
      
   Why call the nothrow version, only to throw later?   
      
        Mem(size_t s) : data(new char[s]) { }   
      
   This is much simpler and achieves the same effect.   
      
   >   
   >      ~Mem()     {   
   >         delete data;   
   >       }   
      
   Again, this should be 'delete[] data;'.   
      
   > };   
      
   Using a 'const' data member effectively prevents assignment, but the   
   class still allows copy construction, which will lead to double delete.   
   You should do something to prohibit copy construction, or write a copy   
   constructor with a suitable semantics.   
      
   Of course, you don't even need to write the Mem class yourself.   
   Just use std::vector with the size as the constructor argument   
   (copying allowed), or std::unique_ptr with 'new char[size]'   
   as the constructor argument (copying prohibited).   
      
   class A   
   {   
        std::vector cstr1;   
        std::unique_ptr cstr2;   
      
   public:   
        A() : cstr1(1000), cstr2(new char[1000]) { }   
   };   
      
   --   
   Seungbeom Kim   
      
      
         [ 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