I wrote some code S s;
... s = {};
, expecting it to end up the same as S s = {};
. However it didn't. The following example reproduces the problem:
#include <iostream>
struct S
{
S(): a(5) { }
S(int t): a(t) {}
S &operator=(int t) { a = t; return *this; }
S &operator=(S const &t) = default;
int a;
};
int main()
{
S s = {};
S t;
t = {};
std::cout << s.a << '\n';
std::cout << t.a << '\n';
}
The output is:
5
0
My questions are:
- Why is
operator=(int)
selected here, instead of "ambiguous" or the other one? - Is there a tidy workaround, without changing
S
?
My intent is s = S{};
. Writing s = {};
would be convenient if it worked. I'm currently using s = decltype(s){};
however I'd prefer to avoid repeating the type or the variable name.
First of all, the case has nothing to do with the "int" version of the assignment operator, you can just delete it. You can actually delete the other assignment operator too as it will be generated by the compiler. IE this kind of type automatically receives copy/move constructors and the assignment operator. (ie they are not prohibited and you are just repeating what the compiler does automatically with explicit notation)
The first case
uses copy initialization:
That is a post-construction copy assignment, yet compilers optimize such simple cases. You should use direction initialization instead:
Note, you can also write:
The second case
What you should write is direct initialization of the right hand side of the copy assignment:
This notation will invoke the default constructor (if there is one), or value initialization for the members (as long as the type is an aggregate). Here is the relevant info: http://en.cppreference.com/w/cpp/language/value_initialization
{}
toint
is the identity conversion ([over.ics.list]/9).{}
toS
is a user-defined conversion ([over.ics.list]/6) (technically, it's{}
toconst S&
, and goes through [over.ics.list]/8 and [over.ics.ref] first before coming back to [over.ics.list]/6).The first wins.
A variation of the trick
std::experimental::optional
pulls to maket = {}
always maket
empty. The key is to makeoperator=(int)
a template. If you want to acceptint
and onlyint
, then it becomesDifferent constraints can be used if you want to enable conversions (you'd probably also want to take the argument by reference in that case).
The point is that by making the right operand's type a template parameter, you block
t = {}
from using this overload - because{}
is a non-deduced context.Does
template<class T> T default_constructed_instance_of(const T&) { return {}; }
and thens = default_constructed_instance_of(s);
count?