jeudi 1 juin 2017

Copy initialization of the form '= {}'

Given the following;-

class Y
{
public:
  Y()              // 1
  // operator X(); // 2
};

class X
{
public:
  X(const Y& rhs); // 3
  X(Y&& rhs);      // 4
};

static void fn()
{
  Y y{};     // Calls (1)

  X j{y};    // Calls (3)
  X k = {y}; // Calls (3)
  X m = y;   // Calls (3)
  X n(y);    // Calls (3)
}

So far, so good. Now, if I enable the conversion operator Y::X(), I get this;-

  X m = y; // Calls (2), and with the result, calls (4)

My understanding is that this happens because (2) is 'less const' than (3) and therefore preferred. Following that, it's natural that (4) would then be called.

My question is, why doesn't the definition X k = {y] change its behaviour in the same way? I know that = {} is technically 'list copy initialisation', but in the absence of a constructor taking an initializer_list type, doesn't this revert to 'copy initialisation' behaviour? ie - the same as for X m = y

Where is te hole in my understanding?

Aucun commentaire:

Enregistrer un commentaire