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,544 of 33,346    |
|    Edward Rosten to MiB    |
|    Re: Exception in Constructor    |
|    18 Sep 12 06:21:58    |
   
   From: firstname.dot.lastname@googlemail.com   
      
   On Mon, 17 Sep 2012 14:24:15 -0700, MiB wrote:   
      
   > Yes, you can avoid the problem. However since "new" is a perfectly   
   > valid construct in C++ and it was used as an example for a   
   > non-tracked resource allocation *only*, your correction completely   
   > misses the point.   
      
   I don't believe it does miss the point. Rewriting your example as:   
      
   class Foo{   
    SomeUntrackedResource a, b, c;   
      
    public:   
    Foo()   
    {   
    //try to allocate a and cleanup on failure.   
      
      
    //try to allocate b and cleanup a and b on failure.   
      
    //try to allocate c and cleanup a and b and con failure.   
    }   
   }   
      
   It is almost certainly easier, cleaner and more reusable to write a   
   small class which manages a single instance of the resource using   
   RAII, and then Foo will simply have three of those objects instead.   
   vector<> is a reasonable example of such a class for memory.   
      
   To illustrate what it may be more like for something not already   
   managed, consider rewriting your example as:   
      
   struct Mem{   
    char* const data;   
      
    Mem(size_t s)   
    :data(new (nothrow) char[s])   
    {   
    if(!data)   
    throw bad_alloc();   
    }   
      
    ~Mem() {   
    delete data;   
    }   
   };   
      
   class A{   
    Mem cstr1;   
    Mem cstr2;   
    Mem cstr3;   
       
    public:   
    A()   
    :cstr1(1000),   
    cstr2(1000000),   
    cstr3(1000000)   
    {   
    }   
   };   
      
   The result is about the same length, and the logic is easier to   
   follow.   
      
   -Ed   
      
      
      
   --   
    [ 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