First of all, you are not using operator=
, rather this is a copy-initialization.
That is, the expression S s1 = 3;
uses non-explicit constructor S(int x)
and also non-explicit and accessible copy constructor S(const S& x)
(hopefully without any additional overhead).
Going further, you can't use S& s1 = 3;
not because you cannot assign 3 to reference, but because the right hand side of assignment is an R-VALUE (that is, a temporary). However, you can extend its lifetime using const reference to l-value, as r-values like very much to be bound by const l-value references:
const S& s1 = 3;
This will work as long as S(int x)
is not marked as explicit
.
Alternatively, (you should not do that at all), you can use r-value reference:
S&& s1 = 3; // implicitly
S&& s2 = S(3); // explicitly
And the error you see trying to compile S& s5;
:
main.cpp:16:5: error: ‘s5’ declared as reference but not initialized
tells you that you cannot just create a variable that is a reference (as opposed to pointers), without initializing it.
But if you had a validly initialized reference, then whenever you would use assignment, only then the operator=
would be invoked:
S s1(1);
S& s1ref = s1;
S s2(2);
s1ref = s2; // s1.operator=(s2);
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…