Friday, September 02, 2005

Valuable interaction

A small doubt of mine - really, it was nothing - but I still wanted to pursue to find out the answer. Okay - I had this doubt when going through the GotW archives - for the un-initiated, GotW stands for "Guru Of The Week" and it has a collection of design puzzles that got discussed on comp.lang.c++.moderated. Herb Sutter maintains an archive of these at his website. In the item pertaining to "forwarding functions", this was what was mentioned. A code example -

class X { };

bool g(X x)
{
   // ...
   return true; // or false
}

bool f(X x)
{
   return g(x);
}

// user code
X xObj;
bool truth = f(xObj);

In cases like this, one would think that the compiler can optimize away the copy of xObj in function 'f'. BUT, the standard now prohibits the compiler from making such an optimization! The reason given was this -

This change was necessary to avoid the problems that can come up when compilers are permitted to wantonly elide copy construction, especially when copy construction has side effects. There are cases where reasonable code may rely on the number of copies actually made of an object.

The only places where a compiler can elide extra copies of objects is during Retrun Value Optimization and for temporaries. (Look into your favorite C++ book for more details on return value optimization). I was not really clear on why totally prohibit such optimizations and also make them standard. Only for types which cared about things such as number of copies made, etc would be affected by such optimization. But for other types, it can incur a performance penalty. Also, if number of copies made is an issue, even the return value optimization can affect code! I did post a query on a usenet group - but that did not generate much light on this issue. I mailed a well known C++ expert who's active on that usenet group - Alf P. Steinbach. He helped me get in touch with Herb Sutter through e-mail and a day later I had got a reply from Herb himself. This is what he had to say -

This was a compromise. Yes, it(RVO) can cause the same change to side effects. But the RVO has clear value that people didn't want to lose, and it's much more constrained so that programmers can learn that copies can be elided in this one place. But in the end it was a compromise.

Well - I was glad that my doubt was a valid one and thrilled to have interacted with gurus like Alf P. Steinbach and Herb Sutter!

2 comments:

  1. Dude.. these guys became guru's following the same path as you( and me :D )

    Yippee I already have interactions with a future guru.

    Jokes aside , that is an interesting observation on Compiler optimisation

    ReplyDelete
  2. sanjiv - hey, thanks dude :D
    but its still a long, long, long, LONG way to go!
    yeah - i thought this was very restrictive for optimizing compilers!

    ReplyDelete

What I want to say is: