Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Optimising Iterator Definitions

This is a (hopefully) really simple question - I have been told recently that using C++ style initialisation is better than traditional (and more common) assignment.

So this code:

std::SomeSTLContainer::const_iterator it = container.begin();
std::SomeSTLContainer::const_iterator itEnd = container.end();

would be 'slower' or less efficient than:

std::SomeSTLContainer::const_iterator it ( container.begin() );
std::SomeSTLContainer::const_iterator itEnd ( container.end() );

I understand the reason for this - the first example causes default construction and initialisation then subsequent assignment rather than specific construction and direct assignment in the second example. However, on modern processors / compilers, does it really make a difference?

like image 872
Konrad Avatar asked Jul 06 '26 06:07

Konrad


2 Answers

I have been told recently that using C++ style initialisation is better than traditional (and more common) assignment.

This is simply wrong.

I understand the reason for this - the first example causes default construction and initialisation then subsequent assignment rather than specific construction and direct assignment in the second example. However, on modern processors / compilers, does it really make a difference?

No, it doesn't make a difference. The C++ standard explicitly allows the assignment in that case to be omitted so that the same code will be produced. In practice, all modern C++ compilers do this.

Additionally, Charles is right: this would never call the assignment operator but rather the copy constructor. But as I've said, even this doesn't happen.

like image 103
Konrad Rudolph Avatar answered Jul 09 '26 07:07

Konrad Rudolph


Your reasoning is not quite correct. Using an '=' in the definition does not cause default construction and assignment. In the 'worst' case, it uses the copy constructor from a temporary generated from the right hand side of the '='.

If the type of the right hand side is (const/volatile aside) of the same type or a derived type of the object being initialized then the two forms of construction are equivalent.

like image 27
CB Bailey Avatar answered Jul 09 '26 08:07

CB Bailey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!