I was playing with the following code.
#include <iostream>
struct To
{
To() = default;
To(const struct From&) {std::cout << "Constructor called\n";}
To(const To&) {std::cout << "Copy constructor called\n";}
};
struct From
{
operator To(){std::cout << "Conversion called\n"; return To();}
};
int main()
{
From f;
To t(f);
To t1 = f;
To t2{To(f)};
}
If I use -std=c++14
both GCC and Clang agree to the following output.
Constructor called
Conversion called
Constructor called
However, If I compile with -std=c++17
, both compilers agree to
Conversion called
Conversion called
Conversion called
I understand that the reduction of several-expected output lines to output 3 lines is due to copy elision, but I can't figure out what changed in C++17 that resulted in this output. What change exactly in standard did initiate this?
To(const struct From&)
requires addingconst
, which is slightly worse than doing nothing to calloperator To()
. If you had hadoperator To() const
orTo(struct From&)
, it would be ambiguous. And in C++14, the conversion operator is usually worse because it would be conversion operator -> copy constructor (even if it ends up elided). Unsure whyTo t1 = f
calls the conversion operator in that case. – Diary