mardi 3 novembre 2015

Overload resolution: assignment of empty braces

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:

  1. Why is operator=(int) selected here, instead of "ambiguous" or the other one?
  2. Is there a tidy workaround?

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.

Aucun commentaire:

Enregistrer un commentaire