473,466 Members | 1,366 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

What happens when a half constructed constructor throws exception

bajajv
152 New Member
Suppose a class has two integers and a function that could throw exception. If the constructor has allocated memory for integers and then it calls the function which throws exception, what will happen to the integers? Will they be released? I am confused becasue the destructor will not run until the object becomes fully constructed.
Apr 25 '12 #1

✓ answered by Banfa

If the constructor allocates memory and then throws an exception (or calls a function that throws an exception) then you will have leaked the memory. The destructor for the object does not get called (because the destructor can not know how much of the object was constructed) however the destructor for any of its bases does get called.

What this means is that you have to be very careful about what you do in constructors, in many ways you have to write them in much the same way as you used to have to write C code, supper defensively catching all errors. In practice this means that you have to ensure your constructor works or that you have handled memory clean up yourself.

For that reason in our company coding standards constructors are supposed to be simple doing the minimum to put the object in a known state.

Note that it is valid to throw an exception from a constructor you just have to be careful how you do it. In fact in some cases it is essential, if you fail to allocate memory in the constructor that the program requires then your only way to indicate the error is to throw an exception.

In the case you give then following the allocation of data if an exception occurs you need to catch it, delete your data and rethrow the exception.

Expand|Select|Wrap|Line Numbers
  1. Example::Example()
  2. {
  3.   try
  4.   {
  5.     // Allocate memory for member variables
  6.     member1 = new int;
  7.     member2 = new int;
  8.  
  9.     function(); // Call a function that may throw an exception
  10.   }
  11.   catch(std::exception& e)
  12.   {
  13.     // And exception occured, clean up this object and rethrow
  14.     delete member1;
  15.     delete member2;
  16.  
  17.     throw;  // Throw by itself rethrows the current exception
  18.   }
  19. }
  20.  
Note that you should never allow a destructor to throw an exception. This is because destructors can often get called while an exception is in progress and the system can not deal with nest exceptions so it just aborts your program.

Also note that you should never call a virtual function from a constructor, you can not be sure the object is fully constructed and until it is fully constructed the vtable used to call virtual functions may not have the correct pointers in it.

3 4621
Banfa
9,065 Recognized Expert Moderator Expert
If the constructor allocates memory and then throws an exception (or calls a function that throws an exception) then you will have leaked the memory. The destructor for the object does not get called (because the destructor can not know how much of the object was constructed) however the destructor for any of its bases does get called.

What this means is that you have to be very careful about what you do in constructors, in many ways you have to write them in much the same way as you used to have to write C code, supper defensively catching all errors. In practice this means that you have to ensure your constructor works or that you have handled memory clean up yourself.

For that reason in our company coding standards constructors are supposed to be simple doing the minimum to put the object in a known state.

Note that it is valid to throw an exception from a constructor you just have to be careful how you do it. In fact in some cases it is essential, if you fail to allocate memory in the constructor that the program requires then your only way to indicate the error is to throw an exception.

In the case you give then following the allocation of data if an exception occurs you need to catch it, delete your data and rethrow the exception.

Expand|Select|Wrap|Line Numbers
  1. Example::Example()
  2. {
  3.   try
  4.   {
  5.     // Allocate memory for member variables
  6.     member1 = new int;
  7.     member2 = new int;
  8.  
  9.     function(); // Call a function that may throw an exception
  10.   }
  11.   catch(std::exception& e)
  12.   {
  13.     // And exception occured, clean up this object and rethrow
  14.     delete member1;
  15.     delete member2;
  16.  
  17.     throw;  // Throw by itself rethrows the current exception
  18.   }
  19. }
  20.  
Note that you should never allow a destructor to throw an exception. This is because destructors can often get called while an exception is in progress and the system can not deal with nest exceptions so it just aborts your program.

Also note that you should never call a virtual function from a constructor, you can not be sure the object is fully constructed and until it is fully constructed the vtable used to call virtual functions may not have the correct pointers in it.
Apr 26 '12 #2
bajajv
152 New Member
Hi Banfa,
Thanks for this info. But what about the auto variables. Consider this class -

Expand|Select|Wrap|Line Numbers
  1. class A
  2. {
  3. public:
  4.  int i;
  5.  int j;
  6.  void fun();
  7.  A();
  8.  ~A();
  9. };
  10.  
  11. A::A() : i(10), j(20)
  12. {
  13.  fun(); //this function throws exception
  14. }
  15.  
If fun() throws exception, then will the memory allocated to i and j be released?
Apr 27 '12 #3
Banfa
9,065 Recognized Expert Moderator Expert
The local variables, such as those in your class are handled by the system. For a stack variable the memory is automatically released when the function exits for a class you are newing if the constructor throws an exception the system releases the memory it just allocated, the new keyword does something like this (note that the new keyword does a 2 stage (working case) operation, call operator new to allocate memory, call the class constructor, the deleted keyword acts similarly in reverse)

Expand|Select|Wrap|Line Numbers
  1. template<typename T>
  2. T* new(std::size_t size)
  3. {
  4.   T* result = NULL;
  5.  
  6.   try
  7.   {
  8.     result = new(sizeof(T));  // Operator new call to allocate memory
  9.  
  10.     if (result != NULL)
  11.     {
  12.       result->T();  // Call the class constructor, it this throws it gets caught below
  13.     }
  14.     else
  15.     {
  16.       throw std::bad_alloc();
  17.     }
  18.   }
  19.   catch(...)
  20.   {
  21.     // Free memory if it was allocated
  22.     if (result != NULL)
  23.     {
  24.       // auto-magically call the destructors for the base of the class that through the exception during construction
  25.       delete result; // Free the allocated memory
  26.       result = NULL;
  27.     }
  28.  
  29.     throw; // Rethrow the issue
  30.   }
  31.  
  32.   return result;
  33. }
  34.  
NOTE: this is not necessarily the actual code for new just effectively how it works.
Apr 27 '12 #4

Sign in to post your reply or Sign up for a free account.

Similar topics

3
by: Thomas | last post by:
Currently we have SQL Server running on a single RAID5 array. The data and the logs are all written to this array. We don't have huge volume of activity, but it is growing. Most activity is from...
2
by: ohaya | last post by:
Hi, I was wondering what happens when width and height in a style (e.g., in a DIV) are set to '0px'? For example something like: style="position: absolute; width: 0px; height: 0px;" ...
0
by: Andreas Klemt | last post by:
Hello, I have this Protected Overrides Function OnBubbleEvent(ByVal source As Object, ByVal args As System.EventArgs) As Boolean a) Return True b) Return False c) Doing nothing... End...
34
by: Ross Reyes | last post by:
HI - Sorry for maybe a too simple a question but I googled and also checked my reference O'Reilly Learning Python book and I did not find a satisfactory answer. When I use readlines, what...
3
tolkienarda
by: tolkienarda | last post by:
hi all i am trouble shooting somthing and i was curious what happens when i try to print the results from a mysql query example $result = mysql_query("SELECT bubbles, fairys FROM holes...
10
by: Digital Puer | last post by:
Sorry for the rudimentary question. I found the following posting online and did not know the answer myself. "Reminds me of a time I had a phone interview concerning a C++ job. Didn't help...
0
by: lemnitzer | last post by:
This is Katrina by the bush bastards in Khaalifornia. I am laughing at the two instances of K, anyone with clue ? dry and wry and vile bushes on fire. Bushes have gone mad with oil. The...
1
by: CF FAN | last post by:
What happens when the read attribute rights of the ColdFusion server to a file is revoked?
7
by: tabla | last post by:
what happens when a sql query get executed containing joins in it.explain in details
3
Fr33dan
by: Fr33dan | last post by:
Hi, Long Version with potentially superfluous details: I have a C# project that I use as a library for multiple programs (The point being it has be tested to and functioned properly). However...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
1
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
0
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated ...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.