In this example where is the C++ assignment operator used rather than the copy constructor ?
- by Bill Forster
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 ?