Dr. Dobb's is part of the Informa Tech Division of Informa PLC

This site is operated by a business or businesses owned by Informa PLC and all copyright resides with them. Informa PLC's registered office is 5 Howick Place, London SW1P 1WG. Registered in England and Wales. Number 8860726.


Channels ▼
RSS

Bug++ of the Month


April 1998/Bug++ of the Month


Defining the lifetime of objects in C++ doesn’t sound like a very exciting subject. I suspect most WDJ readers don’t spend much time worrying about it. But I can assure you, the members of the ISO C++ standardization committee spent a substantial amount of time considering this topic.

Consider the simple code fragment shown below. This routine has a for loop that creates a temporary Bar object on each pass through the loop. The obvious questions are: when does each temporary object get constructed, and when does each temporary object get destroyed?

class Bar {
  //...
};

bool Baz( Bar& b );

int Foo()
{
    for ( int i = 0 ; i < 10 ; i++ ) {
        cout << “Baz returned: “;
        if ( Baz( Bar(i) ) )
            cout << "Success\n";
        else
            cout << "Failure\n";
    }
    //...
}

The creation question in this case is fairly simple: the compiler must generate a temporary Bar() just before it calls Baz() each time in the loop. However, you can imagine many different destruction strategies a program could use. You could destroy the temporary when the if statement completes, or when the for loop exits. You could destroy them when Foo() exits. You could even let the temporaries hang around until the program exits.

As it happens, the ISO standard dictates that the temporaries are normally destroyed as the last step in evaluating the expression that uses the temporary. So in the code shown above, each temporary copy of Bar() is created, passed to function Baz(), then destroyed immediately after Baz() returns.

Knowing the rules here is critical in C++. Creating and destroying objects in C programs simply meant allocating or releasing storage space, and usually didn’t have a big effect on programs. In C++, constructors can do just about anything, such as allocating and freeing key system resources. You really need to have a good understanding of when this happens in your programs. And with the ratification of the C++ standard, the required behavior is now specified.

Borland’s Lifetime Troubles

One of WDJ’s many readers from Down Under, John Burger, noted a problem Borland has with the lifetime of objects under slightly complicated conditions. My demonstration program for John’s bug is shown in apr98.cpp (Listing 1). This program has a static data object named Baz that is local to function Bar(). Local static objects are normally constructed when execution passes through their declaration, and are not destroyed until the program exits.

What complicates the situation here is that the constructor for Baz needs to create two temporary objects of its own. So the first time through this loop, you should see the Foo constructor called three times, once for each of the two temporaries, and once again for the creation of Baz. The two temporary objects should then be immediately destroyed, but Baz should not be destroyed until the program exits.

The next time Bar() is called, no Foo constructors should be called. Baz has already been created, so its constructor doesn’t need to be invoked. Likewise, there wouldn’t be much point in creating the two temporaries, since they aren’t needed.

But as the output shown below indicates, Borland’s 32-bit 5.x compiler gets a little confused about what it should and should not destroy, and when it should be destroyed. The first time through Bar(), the three objects are constructed more or less as expected. Only two destructors are called, but not without some trouble. By my reading, the standard indicates that ordinary temporary variables are supposed to be destroyed in reverse of their creation order. The compiler does just the opposite.

Calling Bar() for the first time...
constructing Foo(2, temp)
constructing Foo(1, temp)
constructing Foo(3, static)
Baz = 3, static
destroying Foo(2, temp)
destroying Foo(1, temp)

Calling Bar() for the second time...
Baz = 3, static
destroying Foo(4199312, H»@)
destroying Foo(0, 0_c)

Terminating...
destroying Foo(3, static)

The trouble really starts on the second pass through Bar(). In this case, the constructor for Baz is not called, since it is static and has already been created. But when the routine exits, the compiler mistakenly tries to destroy the two temporaries! As previously shown in this column, calling the destructor for an invalid object can be disastrous. Imagine a destructor that updates a database or flushes cached data to disk, and you can see how nasty this can get.

Borland’s Response

Borland’s John Wiegley investigated the bug and provided this reply:

We have confirmed that this is a problem with destructor cleanup existing in Borland C++ 5.02 and C++ Builder 1.0, which has been fixed in C++ Builder 3.0. With the newest version of the compiler, the program works as anticipated in the program’s comments.

Borland has announced that Borland C++ will no longer be a separate product. Your upgrade path from Borland C++ v5.02 is C++ Builder 3.0.

Summary

John Burger is to be commended for tracking down this truly nasty bug. In addition to our adulation, John gets a free WDJ t-shirt and our deep appreciation. If you run into a C++ bug that you would like to expose to the light of day, please pass it on to us at [email protected], and we’ll try to use it in a future column.

Correction to Last Month’s Column

The inline code for changes to the <deque> header contained a typographical error. The second line of the void pop_back() section should read:

--_Size;

and not

—_Size;

as printed.

Mark Nelson is a partner in Addisoft Consulting (www.addisoft.com), located in Addison, Texas. Addisoft provides programming services for a wide variety of C and C++ program development tasks. You can reach Mark at [email protected], or at http://web2.airmail.net/markn.

Get Source Code


Related Reading


More Insights






Currently we allow the following HTML tags in comments:

Single tags

These tags can be used alone and don't need an ending tag.

<br> Defines a single line break

<hr> Defines a horizontal line

Matching tags

These require an ending tag - e.g. <i>italic text</i>

<a> Defines an anchor

<b> Defines bold text

<big> Defines big text

<blockquote> Defines a long quotation

<caption> Defines a table caption

<cite> Defines a citation

<code> Defines computer code text

<em> Defines emphasized text

<fieldset> Defines a border around elements in a form

<h1> This is heading 1

<h2> This is heading 2

<h3> This is heading 3

<h4> This is heading 4

<h5> This is heading 5

<h6> This is heading 6

<i> Defines italic text

<p> Defines a paragraph

<pre> Defines preformatted text

<q> Defines a short quotation

<samp> Defines sample computer code text

<small> Defines small text

<span> Defines a section in a document

<s> Defines strikethrough text

<strike> Defines strikethrough text

<strong> Defines strong text

<sub> Defines subscripted text

<sup> Defines superscripted text

<u> Defines underlined text

Dr. Dobb's encourages readers to engage in spirited, healthy debate, including taking us to task. However, Dr. Dobb's moderates all comments posted to our site, and reserves the right to modify or remove any content that it determines to be derogatory, offensive, inflammatory, vulgar, irrelevant/off-topic, racist or obvious marketing or spam. Dr. Dobb's further reserves the right to disable the profile of any commenter participating in said activities.

 
Disqus Tips To upload an avatar photo, first complete your Disqus profile. | View the list of supported HTML tags you can use to style comments. | Please read our commenting policy.