Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where in the C++ Standard is `a = b + {1, 2}` disallowed in the snippet below? [duplicate]

Where in the Standard is a = b + {1, 2} disallowed below?

class complex {
    double re, im;
public:
    complex(double r, double i) : re{ r }, im{ i } {}
    complex& operator+=(const complex& other) { re += other.re; im += other.im; return *this; }
};

inline complex operator+(complex lhs, const complex& rhs)
{
    lhs += rhs;
    return lhs;
}

int main()
{
    complex a{ 1, 1 };
    complex b{ 2, -3 };
    a += {1, 3};          // Ok
    a = b + {1, 2};       // doesn't compile
}
like image 749
Ayrosa Avatar asked Oct 31 '22 10:10

Ayrosa


1 Answers

It is disallowed by not being listed in N3797 §8.5.4 [dcl.init.list]/1 (emphasis mine):

Note: List-initialization can be used

  • as the initializer in a variable definition (8.5)
  • as the initializer in a new expression (5.3.4)
  • in a return statement (6.6.3)
  • as a for-range-initializer (6.5)
  • as a function argument (5.2.2)
  • as a subscript (5.2.1)
  • as an argument to a constructor invocation (8.5, 5.2.3)
  • as an initializer for a non-static data member (9.2)
  • in a mem-initializer (12.6.2)
  • on the right-hand side of an assignment (5.17)

The emphasized bullet point corresponds to your a += {1, 3};. There is no point that fits an addition argument.

like image 136
chris Avatar answered Dec 23 '22 01:12

chris