🚀 go-pugleaf

RetroBBS NetNews Server

Inspired by RockSolid Light RIP Retro Guy

Article View: comp.std.c++
Article #2072

object contruction/destruction in c++, design flaw?

#2072
From: Henk Kampman
Date: Fri, 29 Sep 1995 16:26
79 lines
1919 bytes
Why is the destructor only called for fully contructed objects?
To my oppinion this results in code duplication in the contructor and destructor

For example:


class a
{
public:
   char* mBuffer1;
   char* mBuffer2;
   a();
   ~a();
};

a::a()
{
   mBuffer1 = NULL;
   mBuffer2 = NULL;

   try
   {
      mBuffer1 = new char[1000];
      if(mBuffer1 == NULL)
         throw MemError;

      mBuffer2 = new char[1000];
      if(mBuffer1 == NULL)
         throw MemError;
   }
   catch(...)  // allocation failed
   {
      delete mBuffer1;  
      delete mBuffer2;

      throw;
   }

}

a::~a()
{
   delete mBuffer1;
   delete mBuffer2;
}

If the destructor would be called in case of incomplete contruction, the
code would be much simpler, even in this small example.

a::a()
{
   // initialize for save destruction
   mBuffer1 = NULL;
   mBuffer2 = NULL;

   mBuffer1 = new char[1000];
   if(mBuffer1 == NULL)
      throw MemError;

   mBuffer2 = new char[1000];
   if(mBuffer1 == NULL)
      throw MemError;
 }

// this would be called in case of an exception
// if for example the mBuffer2 allocation failed
a::~a()
{
   delete mBuffer1;
   delete mBuffer2;
}

So, why not call a destructor if an object is partially contructed?

---
[ comp.std.c++ is moderated.  Submission address: std-c++@ncar.ucar.edu.
  Contact address: std-c++-request@ncar.ucar.edu.  The moderation policy
  is summarized in http://dogbert.lbl.gov/~matt/std-c++/policy.html. ]
Technical Details
Message-ID: <henk_kampman-2909951146290001@huisie-ppp1.knoware.nl>
Path: arc1-ca.pugleaf.net!128.32.155.1!matt

Show Full Headers
Complete Article Headers
Path: arc1-ca.pugleaf.net!128.32.155.1!matt
From: henk_kampman@idsys.nl (Henk Kampman)
Newsgroups: comp.std.c++
Subject: object contruction/destruction in c++, design flaw?
Date: 29 Sep 1995 16:26:28 GMT
Organization: ID Systems/TI
Approved: matt@physics2.Berkeley.EDU (Matt Austern)
Message-ID: <henk_kampman-2909951146290001@huisie-ppp1.knoware.nl>
NNTP-Posting-Host: physics2.berkeley.edu