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 << '
';
std::cout << t.a << '
';
}
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.