In the following code, I expect A‘s constructor is called, followed by A‘s copy constructor. However, It turns out only constructor is get called.
// MSVC++ 2008
class A
{
public:
A(int i):m_i(i)
{
cout << "constructor\n";
}
A(const A& a)
{
m_i = a.m_i;
cout << "copy constructor\n";
}
private:
int m_i;
};
int main()
{
// only A::A() is called
A a = 1;
return 0;
}
I guess the compiler is smart enough to optimize away the second call, to initialize the object a directly with the constructor. So is it a standard-defined behavior or just implementation-defined?
It’s standard, but there’s no optimization involved.Actually, I believe there is an optimization involved, but it’s still entirely standard.†
This code:
invokes the converting constructor†† of
A.Ahas a single converting constructorA(int i)that allows an implicit conversion frominttoA.If you prepend the constructor declaration with
explicit, you’ll find the code won’t compile.† After looking at the standard again, I may have been initially wrong.
So in one sense it is very much an optimization. But I wouldn’t worry about it since it is explicitly allowed by the standard and just about every compiler nowadays does the elison.
For a much more thorough treatment on initialization, see this GotW article (#36). The article seems to agree with the above interpretation of the standard:
††
ISO/IEC 14882:2003 C++ Standard reference