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开发者_StackOverflow社区;
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 ?
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.
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).
精彩评论