This question may not be useful in practice, but I would really like to understand how the compiler sees the code behind the scenes, so I asked...
Assume that I am using C++17 or newer. Consider the following code:
class X
{
public:
X() {}
explicit X(const X&) {}
};
int main()
{
X x = X();
}
Since the copy elision is mandatory in C++17 and newer, and since the mandatory copy elision does not check for the accessibility of the copy/move constructor it omits, X x = X();
will always work: the explicit
ness of the copy constructor will be ignored and X()
will be used to construct the object represented by x
directly. However, this is not the case for C++14 or earlier: in those older versions, the explicit
ness of the copy constructor will stop X x = X();
even when the optimization for copy elision is on. Hence, I think there must be a difference between the implementations in pre-C++17 and in post-C++17 for this: for the former, the checking of the accessibility seems to happen logically before the copy elision, whereas for the latter, the copy elision seems to happen logically before the checking of the accessibility.
What I would like to ask is how the latter implementation might be done. How might the mandatory copy elision in C++17 and newer be implemented so that the compiler knows where to conduct copy elision while bypassing the checks on the accessibility of the constructor being omitted?