I have the following code:
#include <iostream>
using namespace std;
class foo
{
public:
foo(int a, int b) :
a_(a), b_(b)
{ cout << "regular const" << endl; }
foo(const foo& f) :
a_(f.a_), b_(f.b_)
{ cout << "copy const" << endl; }
foo& operator=(const foo& rhs)
{cout << "copy= const" << endl; a_ = rhs.a_; b_ = rhs.b_; return *this; }
int a_, b_;
};
void bar(foo f)
{ }
int main()
{
foo f1(10, 20);
cout << "------" << endl;
bar(f1);
cout << "------" << endl;
bar(foo(11, 22)); // line 29
cout << "------" << endl;
bar({13, 23}); // line 32
cout << "------" << endl;
}
I get the following output:
$ ./a.out
regular const
------
copy const
------
regular const
------
regular const
------
For line 29 and line 32, I was expecting a temp object to be created in main (invoking regular constructor) and then a copy constructor being invoked when passed to bar(). From the output I see the compiler doing some optimization, and guessing maybe just creating the object on the stack when calling bar() and only regular constructor being invoked. Can someone please help me understand what type of optimization is being done or what is happening under the hood.
Is calling bar() using lines 29 and 32 equivalent as far as generated code? I understand line 29 is more readable.
I changed bar() as follows:
void bar(const foo& f)
{ }
I get the same output for lines 29 and 32. In this case where is the object being created?
Thank you, Ahmed.