From: DerTopper@web.de   
      
   [snip]   
      
   On 9/17/12 Stuart wrote:   
   > The C++ way of doing this would be:   
   >   
   > #include    
   > class A   
   > {   
   > private:   
   > std::vector cstr1;   
   > std::vector cstr2;   
   > std::vector cstr3;   
   > public:   
   > A ()   
   > {   
   > // Phase (I): Allocation of   
   > // Ressources.   
   > //   
   > // These allocations may throw   
   > // std::bad_alloc, but we don't   
   > // don't have to worry about   
   > // unreleased memory since these   
   > // variables will be cleaned up   
   > // when an exception is thrown.   
   > std::vector temp_cstr1;   
   > temp_cstr1.reserve(1000);   
   > std::vector temp_cstr2;   
   > temp_cstr2.reserve(1000000);   
   > std::vector temp_cstr3;   
   > temp_cstr3.reserve(1000000);   
   >   
   > // Phase (II): Transfer of   
   > // Ownership of   
   > // Ressources.   
   > //   
   > // The following swaps are   
   > // guaranteed not to throw,   
   > // so the constructor will   
   > // finish successfully once   
   > // it reaches these lines.   
   > cstr1.swap(temp_cstr1);   
   > cstr2.swap(temp_cstr2);   
   > cstr3.swap(temp_cstr3);   
   > }   
   > };   
      
   Um, the separation of the constructor into two phases is actually not   
   necessary because the constructor treats the member variables of the   
   partially constructed object like local variables, e.g. they get   
   destroyed in case the constructor is left via an exception. I remember   
   that I read somewhere that this is a distinctive feature of C++, but I   
   cannot tell which part of the C++ standard mandates this.   
      
   The technique of splitting an operation into a throwing and a   
   non-throwing part is nevertheless an important technique to know. It is   
   useful for writing exception safe assignment operators.   
      
   Regards,   
   Stuart   
      
      
   --   
    [ 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)   
|