Is this undefined behavior when calling private functions in the list of initializers?

Consider the following code:

struct Calc
{
   Calc(const Arg1 & arg1, const Arg2 & arg2, /* */ const ArgN & argn) :
      arg1(arg1), arg2(arg2), /* */ argn(argn), 
      coef1(get_coef1()), coef2(get_coef2()) 
   {
   }

   int Calc1();
   int Calc2();
   int Calc3();

private:
  const Arg1 & arg1;
  const Arg2 & arg2;
  // ...
  const ArgN & argn;

  const int coef1; // I want to use const because 
  const int coef2; //      no modification is needed.

  int get_coef1() const {
     // calc coef1 using arg1, arg2, ..., argn;
     // undefined behavior?     
  }
  int get_coef2() const {
     // calc coef2 using arg1, arg2, ..., argn and coef1;
     // undefined behavior?
  }

};

struct Calcnot fully defined when I call get_coef1and get_coef2 Is this code valid? Can I get UB?

+5
source share
3 answers

12.6.2.8: - ( , 10.3) . , typeid (5.2.8) dynamic_cast (5.2.7). , ctor- ( , ctor-) mem , undefined.

, , . , , , .

+8

, , , undefined. . .

+3

undefined, , - . , , , . :

struct Foo
{
  int a, b;
  int c;
  Foo(): c(1), a(1), b(1) {}
};

In this constructor, the variables are initialized in the order a, b, then c , the order in the list means nothing. Therefore, if you want the value to abe initialized using some calculations on band c, you need to move the declaration ato the point after band c.

0
source

All Articles