tags:

views:

85

answers:

2

As part of an ongoing process of trying to upgrade my C++ skills, I am trying to break some old habits. My old school C programmer inclination is to write this;

void func( Widget &ref )
{
    Widget w;  // default constructor
    int i;
    for( i=0; i<10; i++ )
    {
        w = ref;  // assignment operator 
        // do stuff that modifies w
    }
}

This works well. But I think the following is closer to best practice;

void func( Widget &ref )
{
    for( int i=0; i<10; i++ )
    {
        Widget w = ref; // ??
        // do stuff that modifies w
    }
}

With my Widget class at least, this works fine. But I don't fully understand why. I have two theories;

1) The copy constructor runs 10 times.
2) The copy constructor runs once then the assignment operator runs 9 times.

Both of these trouble me a little. 2) in particular seems artificial and wrong. Is there a third possibility that I am missing ?

+8  A: 

Your first theory is correct: the copy constructor is invoked ten times. This:

Widget w = ref;

is (almost) the same as:

Widget w(ref);

The first is called copy initialization; the second is called direct initialization. Both invoke the copy constructor. The main difference between the two is that the first is invalid if the copy constructor is declared explicit, while the second is valid so long as there is an accessible copy constructor.

You can verify this by declaring and defining both a copy constructor and a copy assignment operator for Widget, and seeing how many times each is called.

James McNellis
Thank you very much.
Bill Forster
James I am going to "unaccept" this and accept Lorenzo's answer. I hesitated about doing this as I hate rudeness. But I hit on a solution, I've browsed your answers and upvoted some of them so you get a net win anyway. I discovered you have provided many succinct, grammatical and useful answers, well done. Reviewing an expert's answers turns out to be educational, I will do this more! Why the unaccept/accept? Well the thing that was confusing me was that I didn't understand how something that already exists can be constructed. Lorenzo addresses that. I don't blame you for not reading my mind!
Bill Forster
@Bill: It's not rude at all :-) I'm just glad you got your question answered. That's all that really matters.
James McNellis
+2  A: 

Of course the copy constructor runs 10 times! When you iterate the for(;;) cycle, at each iteration the variables declared inside the braces will go out of scope. If Widget has a destructor, it will be called 10 times (possible performance hit).

Lorenzo
Ok I believe it is obvious to you. To me it wasn't obvious because I think of the contructor as something that constructs something that doesn't exist.
Bill Forster
When you have this kind of doubts, my suggestion is to write small test programs that output some console output in constructors and in destructors, so the actual program flow will be clear. I still use this technique when I have doubts.
Lorenzo
That's what I normally do too. This time I spent half an hour perusing Lippman instead. And when I couldn't find an explanation of this apparently simple issue, I thought it was worth sharing the question. I thought that was what the site was for.
Bill Forster
Thanks for your extra explanation in the body of your answer. With that it now seems obvious to me too so +1.
Bill Forster
It is indeed the meaning of this site, even "obvious" questions are often good question. And the answer is really a good one only if the explanation seems obvious even for the person who asked it!
Lorenzo
Yes Lorenzo, we got off to a bad start but your improved answer is very good and gets right to the heart of the issue. The truth is I have been coding in C, and C++ in the "C with classes" sense for literally decades. But until recently I would always put all my local vars at the top of each function, which was normal practice back in the day. So now I am trying to change that but I haven't developed any "feel" yet for local variables in narrower scopes, particularly when those narrow scopes are loops.
Bill Forster
Sorry if my answer seemed too rude! I'm taking the "agile" answering way to start with the very core answer, then improving it by editing. There's only one way to decide where to declare a variable: lifetime. Your object should be instanced only when and if required, and destroyed by going out of scope as soon it is no longer needed. This is especially true when using exception handling! However you have to be careful to not introduce unnecessaries performance penalties just to have a "well structured code".
Lorenzo
"If Widget has a destructor" -> every class has a destructor, it's just that the default destructor doesn't do anything ;)
FredOverflow
@FredOverflow: while this is "academically" true, if the class does not declare a destructor, there is not a base class and inside the class there aren't objects that have destructors themselves, the compiler actually does... nothing: if you look at the generated assembly code, there isn't some "empty default destructor". This is important, because it means that there's no performance penalty!
Lorenzo
You cannot draw any general, meaningful conclusions about the C++ language from assembly code that a particular compiler chooses to spit out. For example, people often talk about vtables and vptrs, but there is no such thing in the C++ language. Anyway, both our "theories" lead to the same conclusion, so no big deal I guess :)
FredOverflow
Sure, it is always implementation-dependent. However in real world, we can assume some implementation behavior especially when thinking of performance and optimization.
Lorenzo
Hi Lorenzo, your answer has really fixed a bug in my mind with respect to autos in loops. They go out of scope at each iteration. Of course! Bearing that in mind, I decided I should really accept your answer because it directly addresses the confusion that lead to my question. I hesitated because I didn't want to punish James' helpful and good answer, but then I realized I could address that by reviewing some other answers of his and upvoting some of them so he still gets a net win. Sheesh I'm getting longwinded in my old age.
Bill Forster
Hi Bill, I'm glad that this helped you to better clarify the lifetime of objects in cycles. I voted up James, too!
Lorenzo