Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

relations between all kinds of initialization and constructions?

I am asking if

Type t{...};

and

Type t({...});

and

Type t = {...};

are equivalent? If one works, the other should also work with the same results?

If no explicit modifier, are they equivalent?

like image 772
user1899020 Avatar asked Mar 10 '23 13:03

user1899020


1 Answers

No, all three forms are distinct, and may be well-formed or ill-formed independently under different circumstances.

Here's an example where first form compiles, but 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's the example where second form compiles, but 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
}

Here's an example, courtesy of @T.C., where third form compiles, but first and second do not:

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
}
like image 59
Igor Tandetnik Avatar answered Apr 06 '23 11:04

Igor Tandetnik