Can a default function return auto?
auto & operator =(const example &) = default; auto & operator =(example &&) = default;
Are those declarations considered legal?
No.
[dcl.spec.auto] ... If the declared return type of the function contains a placeholder type, the return type of the function is deduced from non-discarded return statements, if any, in the body of the function ([stmt.if]).
A defaulted function definition does not have a body, which conflicts the quoted rule. There is nothing that the return type could be deduced from and there is no rule that states what that type would be in this case.
operator<=>
has an exceptional rule specifying what the return type will be when auto
is used as shown in Caleth's answer, but operator=
does not have such rule. I see no reason such rule couldn't be introduced to allow auto in defaulted assignment operators.
In C++20, Yes1
Let
R
be the declared return type of a defaulted three-way comparison operator function, and letxi
be the elements of the expanded list of subobjects for an objectx
of type C`.
- If
R
isauto
, then letcvi Ri
be the type of the expressionxi <=> xi
. The operator function is defined as deleted if that expression is not usable or ifRi
is not a comparison category type ([cmp.categories.pre]) for anyi
. The return type is deduced as the common comparison type (see below) ofR0, R1, …, Rn−1
.
[class.spaceship/2]
Before C++20, No
A function definition of the form: attribute-specifier-seq opt decl-specifier-seq opt declarator virt-specifier-seq opt
= default ;
is called an explicitly-defaulted definition. A function that is explicitly defaulted shall
- be a special member function,
- have the same declared function type (except for possibly differing ref-qualifiers and except that in the case of a copy constructor or copy assignment operator, the parameter type may be “reference to non-const
T
”, whereT
is the name of the member function's class) as if it had been implicitly declared, and
[dcl.fct.def.default]
(emphasis added)
- But only
<=>
. A defaulted==
must returnbool
, and assignment has similar restrictions as previous standards.
if
F
is an assignment operator, and the return type ofT1
differs from the return type ofT2
orT1
's parameter type is not a reference, the program is ill-formed;
[dcl.fct.def.default]