Comments (9)
  • Add a Comment
  • Edit
  • More Actions v
  • Quarantine this Entry

1 hstong commented Permalink

Mystery #1:<br /> In<br /> <div class="jive-quote">X( int i ) : y_( i ),z_(1.23) { X(); }</div> you are constructing a temporary and not delegating to the default constructor (as intended).

2 Michael_Wong commented Permalink

Good work!. You are right. The temporary will get created, and destroyed at the end of scope. No delegation.

3 hstong commented Permalink

Mystery #2:<br /> Among other things, destructors for the members of X will be called twice if init() throws an exception.<br /> This is the worst solution because it has undefined behaviour.

4 Michael_Wong commented Permalink

Even if an exception is not thrown, this code has problems ...<br /> But you are right in that an exception would be even more problematic.

5 hstong commented Permalink

The subobjects did not have their destructors called. There can be a memory leak if a subobject allocated memory dynamically.

6 Michael_Wong commented Permalink

Not bad, and you are definitely dancing around the whole issue of object life times which is where the answer lies.<div>&nbsp;</div> My response to this is that there is indeed a memory leak, but it need not be from any dynamic memory allocation of subobjects (which I assume you mean embedded members Y and Z).

7 hstong commented Permalink

I think that the standard is a bit vague on what constitutes a "reuse" of storage. This makes it hard for me to tackle the issue with object lifetimes directly. Anyhow, another case where the placement new solution above will not work is when the object of type X is actually a base class subobject itself.

8 Michael_Wong commented Permalink

I think I have to give it to you for the many cases you described. What I was looking for is not that far from what you were describing. It is that now in Mystery #2, we have an imbalance in the number of constructor and destructors, which is always a sign that something bad will happen. May be not immediately, but likely when you add any more complexity to the class (such as more members). <div>&nbsp;</div> Just counting the construction of X, you will see that there are 2 constructor calls, and only one destructor call. This, as you said, is the worst solution. Well done.

9 steven.zhang373 commented Permalink

This article is translated into Chinese at: <br /> https://www.ibm.com/developerworks/mydeveloperworks/blogs/12bb75c9-dfec-42f5-8b55-b669cc56ad76/entry/c_0x__e5_a7_94_e6_89_98_e6_9e_84_e9_80_a0_e5_87_bd_e6_95_b05?lang=en