I was confused why my program behaved in an unexpected way. Then I wrote this simplified version of it and discovered that there is a constructor call "missing".
template <class T>
class A
{
public:
A () {std::cout << "default" << "\n";} // default ctor
A (const A& src) // copy ctor
{
std::cout << "copy" << "\n";
}
friend A<T> operator<<(A& a, unsigned i)
{
std::cout << "x1" << "\n";
A tmp;
std::cout << "x2" << "\n";
return tmp;
}
};
int main()
{
A<int> a1;
A<int> a2(a1 << 2);
}
Output
default
x1
default
x2
What I had expected was
default
x1
default
x2
copy
as the r-value returned by a1 << 2
would be passed into the const A&
parameter of the copy ctor. But that is not what happens. And if not that then at least I would expect
default
x1
default
x2
default
because I would have thought that the constructor for a2
would need to be called.
What is going on here?