473,672 Members | 2,568 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Challenging GotW 66's moral

Hello everyone,
In GotW #66, one of the moral is the exception handler of constructor
should not do any like resource free task. I do not agree. Here is the
quoated moral and my code to prove this moral will have memory leak.

Anything wrong with my analysis?

http://www.gotw.ca/gotw/066.htm

Moral #1: Constructor function-try-block handlers have only one
purpose -- to translate an exception. (And maybe to do logging or some
other side effects.) They are not useful for any other purpose.
Expand|Select|Wrap|Line Numbers
  1. class A
  2. {
  3. private:
  4.  
  5. int* p;
  6.  
  7. public:
  8.  
  9. A()
  10. try
  11. {
  12. p = new int[10];
  13.  
  14. // there are some other exceptions here
  15.  
  16. }
  17. catch (bad_alloc)
  18. {
  19. // do not delete since bad_alloc means memory pointed by p is
  20. not allocated
  21. }
  22. catch (...)
  23. {
  24. // if we do not delete p, there will be memory leak
  25. // at this point, we are conflicting with Gotw 66's moral 1
  26. if (p) delete[] p;
  27. }
  28. }
  29.  

thanks in advance,
George
Dec 27 '07 #1
4 1245
On Dec 27, 1:54 am, George2 <george4acade.. .@yahoo.comwrot e:
Hello everyone,

In GotW #66, one of the moral is the exception handler of constructor
should not do any like resource free task. I do not agree. Here is the
quoated moral and my code to prove this moral will have memory leak.

Anything wrong with my analysis?

http://www.gotw.ca/gotw/066.htm

Moral #1: Constructor function-try-block handlers have only one
purpose -- to translate an exception. (And maybe to do logging or some
other side effects.) They are not useful for any other purpose.

[code]
class A
{
private:

int* p;

public:

A()
try
{
p = new int[10];

// there are some other exceptions here

}
catch (bad_alloc)
{
// do not delete since bad_alloc means memory pointed by p is
not allocated
}
catch (...)
{
// if we do not delete p, there will be memory leak
// at this point, we are conflicting with Gotw 66's moral 1
if (p) delete[] p;
at this point, p would never be 0 (even if the new allocation in ctor
body was not processed yet).
Pointer p, as is, has either a valid address or garbage in it.
As far as that catch block is concerned, it'll always delete [] p.

So how about:

A() : p(0)
try
{
p = new int[10];
}
catch(...)
{
if (p) delete[] p;
}

have you considered shared_ptr instead of doing decadent new
allocations?
Dec 27 '07 #2
On 2007-12-27 07:54, George2 wrote:
Hello everyone,
In GotW #66, one of the moral is the exception handler of constructor
should not do any like resource free task. I do not agree. Here is the
quoated moral and my code to prove this moral will have memory leak.

Anything wrong with my analysis?

http://www.gotw.ca/gotw/066.htm

Moral #1: Constructor function-try-block handlers have only one
purpose -- to translate an exception. (And maybe to do logging or some
other side effects.) They are not useful for any other purpose.
Expand|Select|Wrap|Line Numbers
  1. class A
  2. {
  3. private:
  4. int* p;
  5. public:
  6.     A()
  7.     try
  8.     {
  9.         p = new int[10];
  10.         // there are some other exceptions here
  11.     }
  12.     catch (bad_alloc)
  13.     {
  14.         // do not delete since bad_alloc means memory pointed by p is
  15. not allocated
  16.     }
  17.     catch (...)
  18.     {
  19.         // if we do not delete p, there will be memory leak
  20.         // at this point, we are conflicting with Gotw 66's moral 1
  21.         if (p) delete[] p;
  22.     }
  23. }
  24.  
The advice assumes that you follow other advices, such as using RAII and
writing exception safe code, if you did you would never end up in a
situation where you need to free any memory in a catch-block. One
example of that would be to replace p with a smart-pointer.

--
Erik Wikström
Dec 27 '07 #3
George2 <ge************ *@yahoo.comwrot e:
Hello everyone,
In GotW #66, one of the moral is the exception handler of constructor
should not do any like resource free task. I do not agree. Here is the
quoated moral and my code to prove this moral will have memory leak.

Anything wrong with my analysis?
Your idea is covered in the article:

"--But wait!" I hear someone interrupting from the middle of the
room. "I don't agree with Moral #1. I can think of another possible
use for constructor function-try-blocks, namely to free resources
allocated in the initializer list or in the constructor body!"

Sorry, nope. After all, remember that once you get into your
constructor try-block's handler, any local variables in the
constructor body are also already out of scope, and you are
guaranteed that no base subobjects or member objects exist any more,
period. You can't even refer to their names.

Maybe the output to the following will help:

class B {
public:
B() { cout << "B()\n"; }
~B() { cout << "~B()\n"; }
void foo() { cout << "B::foo()\n "; }
};

class A
{
private:
B b;
public:
A() try: b()
{
throw -1;
}
catch (...)
{
b.foo();
}
};

int main() {
try {
A a;
}
catch ( ... ) { }
}

Note that B::foo() is called *after b's destructor has already been
called.* Thus invoking undefined behavior.
http://www.gotw.ca/gotw/066.htm

Moral #1: Constructor function-try-block handlers have only one
purpose -- to translate an exception. (And maybe to do logging or some
other side effects.) They are not useful for any other purpose.
Expand|Select|Wrap|Line Numbers
  1. class A
  2. {
  3. private:
  4. int* p;
  5. public:
  6.     A()
  7.     try
  8.     {
  9.         p = new int[10];
  10.         // there are some other exceptions here
  11.     }
  12.     catch (bad_alloc)
  13.     {
  14.         // do not delete since bad_alloc means memory pointed by p is
  15. not allocated
  16.     }
  17.     catch (...)
  18.     {
  19.         // if we do not delete p, there will be memory leak
  20.         // at this point, we are conflicting with Gotw 66's moral 1
  21.         if (p) delete[] p;
Expand|Select|Wrap|Line Numbers
  1.  
  2. 'p' doesn't exist once you get in the catch block. Yes, in your example
  3. it happens to still point to the right place, but there is no guarantee
  4. that this is true. Frankly, I'm surprised the code even compiled.
  5.  
  6.         
  7.                     }
  8. }
  9.  
  10.  
>

thanks in advance,
George
Dec 27 '07 #4
On Dec 27, 4:58 am, Salt_Peter <pj_h...@yahoo. comwrote:
On Dec 27, 1:54 am, George2 <george4acade.. .@yahoo.comwrot e:
Hello everyone,
In GotW #66, one of the moral is the exception handler of constructor
should not do any like resource free task. I do not agree. Here is the
quoated moral and my code to prove this moral will have memory leak.
Anything wrong with my analysis?
http://www.gotw.ca/gotw/066.htm
Moral #1: Constructor function-try-block handlers have only one
purpose -- to translate an exception. (And maybe to do logging or some
other side effects.) They are not useful for any other purpose.
[code]
class A
{
private:
int* p;
public:
A()
try
{
p = new int[10];
// there are some other exceptions here
}
catch (bad_alloc)
{
// do not delete since bad_alloc means memory pointed by p is
not allocated
}
catch (...)
{
// if we do not delete p, there will be memory leak
// at this point, we are conflicting with Gotw 66's moral 1
if (p) delete[] p;

at this point, p would never be 0 (even if the new allocation in ctor
body was not processed yet).
Pointer p, as is, has either a valid address or garbage in it.
As far as that catch block is concerned, it'll always delete [] p.

So how about:

A() : p(0)
try
{
p = new int[10];}

catch(...)
{
if (p) delete[] p;

}

have you considered shared_ptr instead of doing decadent new
allocations?

obviously, clarification is required since you can't allocate an array
using boost::shared_p tr.
replace the array with a std:vector or use boost::scoped_a rray.
Dec 27 '07 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
1550
by: Srini | last post by:
Hello all, I was going thru the GotW archives where I had a doubt in this particular item. http://www.gotw.ca/gotw/027.htm There is a mention about a subtle change to the standard in July 1997. According to that, the only places a compiler can eliminate making copy of objects is in case of return value optimization and temporary
11
1416
by: George | last post by:
Was my question too challenging for everyone? I thought I would get a much quicker response, complete with witty and (sometimes) condescending remarks Here's my question again, in case you missed it How do I reload a page Notice I did not ask "How do I *refresh* a page". I have no interest in the header meta refresh as this clears out the data I need to show. Also, Response.Redirect does me no good. It completely bypasses the data as...
5
1599
by: Olaf Baeyens | last post by:
I have another problem, maybe it is simple to fix. I have this: byte Test=new byte; But I now want to have a second pointer Test2 to point to a location inside this Test. But with no copying. Something like this.
18
1578
by: Frankie | last post by:
I have been hired to go to a former client of mine and train their staff programmers on ASP.NET. These guys have only Mainframe, MS Access, SQL Server, and VB6 desktop application development experience (with absolutely no HTML or Web application experience). Before jumping into any code I think it's important to get them to understand the fundamental differences and unique challenges presented by Web application development (independent...
2
1350
by: Wayne | last post by:
This is a copy of a message I previously posted in a Microsoft Access Newsgroup, but it was suggested to me that my problem is ASP related and not Access, and hence I'm posting in this newsgroup now instead. Hi everyone, I've got quite a specific query that I'm trying to resolve with Microsoft Access and I'm hopeful someone out there can offer a solution to my problem. I have records that I'm displaying on a web page from an Access...
5
1228
by: alainpoint | last post by:
Hi, I have what in my eyes seems a challenging problem. Thanks to Peter Otten, i got the following code to work. It is a sort of named tuple. from operator import itemgetter def constgetter(value): def get(self): return value return get def createTuple(*names):
0
1383
by: CoreyWhite | last post by:
Dr. Elsebeth Baumgartner (born May 12, 1955) is a former attorney and current CEO of Cleveland Genomics, Inc. (which provides DNA sequencing services), and has doctorate degrees both in law and in pharmacy. Dr. Baumgartner graduated first in her entering class from the University of Toledo College of Law. She is a Christian and the mother of two adult daughters by her husband, pharmacist Joseph Baumgartner. She is currently facing criminal...
4
1072
by: George2 | last post by:
Hello everyone, In GotW #66, one of the moral is the exception handler of constructor should not do any like resource free task. I do not agree. Here is the quoated moral and my code to prove this moral will have memory leak. Anything wrong with my analysis? http://www.gotw.ca/gotw/066.htm Moral #1: Constructor function-try-block handlers have only one purpose -- to translate an exception. (And maybe to do logging or some other...
0
868
by: puzzlecracker | last post by:
It is per Sutter's GotW #47 article. I don't understand why if a U object is destroyed due to stack unwinding during to exception propagation, T::~T will fail to use the "code that could throw" path even though it safely could. Code from the article: // The wrong solution // T::~T() {
0
8404
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8931
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8828
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
8680
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7446
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5705
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
1
2819
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 we have to send another system
2
2063
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1816
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.