The relationship between all kinds of initialization and constructions?

I ask if

Type t{...};

and

Type t({...});

and

Type t = {...};

are equivalent? If someone works, should another also work with the same results?

If there is no modifier explicit, are they equivalent?

+4
source share
1 answer

No, all three forms are different and can be well formed or poorly formed independently in different circumstances.

Here is an example where the first form compiles and the second and third do not:

class Type {
public:
    explicit Type(int, int) {}
};

int main()
{
    Type t1{1, 2};     // Ok
    Type t2({1, 2});   // error
    Type t3 = {1, 2};  // error
}

Here is an example where the compilation of the second form, but the first and third do not:

class Pair {
public:
    Pair(int, int) {}
};

class Type {
public:
    Type(const Pair&) {}
};

int main()
{
    Type t1{1, 2};     // error
    Type t2({1, 2});   // Ok
    Type t3 = {1, 2};  // error
}

, @TC, , :

struct StrangeConverter {
    explicit operator double() = delete;
    operator float() { return 0.0f; }
};

int main() {
  StrangeConverter sc;
  using Type = double;
  Type t1{sc};     // error
  Type t2({sc});   // error
  Type t3 = {sc};  // Ok
}
+7

Source: https://habr.com/ru/post/1672830/


All Articles