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

Conversations:It's an Object-ful Lifetime


December 2002 C++ Experts Forum/Conversations


It was a few days before the holidays. For once, there were no deadline pressures — all the projects I had been working on had wrapped up on schedule.

I resorted to my favorite pastime of skimming through the source repository. I frequently learned new techniques — and techniques to avoid — while studying other programmers' code. I came across an interesting tidbit, which I distilled into this small program:

class T
{
public:
 T & ref() { return *this; }
};

void f( T & );

int main()
{
 f( T().ref() );
}

At first, I didn't see the point of the ref() function, so I removed the call to it — I figured it should work:

int main()
{
  f( T() );
}

When I compiled it, though, the compiler promptly spat out an error about binding a temporary to a non-const reference. I mentally smacked my palm against my forehead — of course that wasn't allowed! I recalled the Guru's explanation, when I had first stumbled on the problem.

"One reason for the prohibition is to prevent subtle bugs," she had said. "Consider, my child, the following parable:"

class U
{
// ... whatever ...
};

void takesAndModifiesU( U & u )
{
 // performs actions that modify the state of u
}

class V
{
public:
 operator U();
};

void g()
{ 
 V v;
 // ...
 takesAndModifiesU( v );
 // ...
}

"If the binding were allowed, the compiler would invoke the conversion operator, creating a temporary U object. This unnamed temporary object would then be passed to takesAndModifiesU, modified, and then discarded after the function call was completed. The original object, v, would be untouched — to the great puzzlement of the scribe who wrote that function."

I was still puzzled, though. I couldn't see how the original statement f( T().ref() ); could compile — I was still binding a temporary object to a non-constant reference.

"You must think beyond constancy, my child," the Guru's voice — for real, not a memory — startled me. "Think instead of lvalues and rvalues. The Holy Standard tells us that an explicit type conversion of the form T() creates an rvalue. An rvalue can only be bound to a constant, non-volatile reference, but an lvalue has no such restriction. On the other hand, the result of a function that returns a reference is an lvalue [1]. Therefore the compiler can bind the result of ref() to the non-constant reference."

"So, as long as I call a function that returns a reference, I'm OK," I replied. "Hey — the assignment operator returns a reference, so I could write f( T() = T() );. Sweet!" I enthused. "I can think of lots of uses for that technique."

"Beware, my child. Such unusual techniques can be dangerous and should not be used lightly. Indeed, there is at least one parable I can think of, involving object lifetimes, which would lead to undefined behavior."

"And that would be..." I prompted.

"For you to meditate upon, after lunch," the Guru replied smoothly. In the distance, I could see some of our co-workers preparing to go to the department's holiday lunch. I grabbed my coat, joined the group, and we headed out to a local restaurant.

Somehow, we actually managed to avoid talking shop at lunchtime. Much of the discussion centered on our favorite holiday movies, comparing the various remakes of Miracle on 34th Street, and whether Alistair Sim or Patrick Stewart made a better Scrooge. (My vote was for Stewart.) Bob surprised me, though — I figured his favorite character would be the Grinch, but instead he waxed poetic on It's A Wonderful Life.

When we got back from lunch, I was well sated. I sat down at my desk and started contemplating what the Guru might have been getting at. Finally, as I was struggling to keep my eyes open, I figured it out:

class U
{
 T& t_;
public:
 U( T & t ) : t_( t ) { } 
};

{ // ... some block scope ...
 U u( (T() = T()) );
 // ... 
}

As soon as the u object was finished construction, the temporary object's lifetime would come to an end, and the u object would be left with a dangling reference.

It would be as if the T object never existed, I mused as I drifted off.

"All right, George," I heard the Guru's voice, "you've got your wish. You've never been born."

"Huh? Who's George?" I turned to the Guru.

"You are, of course," the Guru answered. As soon as I saw her, I knew I was dreaming — one of those dreams where you know it's a dream, but you go along with it anyway. "You're George Bailey. The object you created never existed. It's my job to show you what can happen when you deal with undefined behavior."

In the distance, I could see a sign: "Welcome to Bobville."

"Bobville?" I asked, dreading the answer.

"The town is run by your nemesis, Bob," the Guru said. "He's also the owner of the bank, and the head of the software department. Let's take a walk along the main street."

As we walked along, I saw unspeakable horrors — monolithic code blocks, variables named i and j, and businesses advertising "Null Pointers Dereferenced Here." On one street corner, I saw some programmers shamelessly copying-and-pasting code.

I spotted Kerry driving a cab. I flagged him down.

"Get me out of here, Kerry," I shouted as I climbed in the cab. "Take me back to the office, where we write sensible code."

"Kerry? My name's Ernie. I don't know about code; I just drive a cab." We drove past Wendy, dressed in a cop's uniform. Kerry waved to get her attention. Knowing it was a dream and I wasn't supposed to see his actions, I ignored him.

We pulled up in front of a run-down office building. I leaped out and ran inside. I found a whiteboard, which had the offending code written on it, and rewrote it:

{ // ... some block scope ...
 T tmp;
 U u( tmp );
}

As soon as I put the marker down, I snapped awake.

"Whoa!" I said to myself, as I went to the lunchroom to get the strongest coffee I could find.

Note

[1] ISO/IEC 14882:1998(E), "International Standard, Programming Languages — C++", clauses 5.2.3, 8.5.3, and 3.10 respectively.

Jim Hyslop is a senior software designer at Leitch Technology International Inc. He can be reached at [email protected].


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.