c++ - 在初始化列表中调用私有(private)函数的情况下,它是未定义的行为吗?

标签 c++ constructor constants undefined-behavior

考虑以下代码:

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?
  }

};
当我调用 get_coef1get_coef2 时,

struct Calc 未完全定义 这个代码有效吗?我可以获得 UB 吗?

最佳答案

12.6.2.8: Member functions (including virtual member functions, 10.3) can be called for an object under construction. Similarly, an object under construction can be the operand of the typeid operator (5.2.8) or of a dynamic_cast (5.2.7). However, if these operations are performed in a ctor-initializer (or in a function called directly or indirectly from a ctor-initializer) before all the mem-initializers for base classes have completed, the result of the operation is undefined.

所以你可以用这种方式初始化你的类成员,但不能初始化基类。而且,正如其他人指出的那样,如果您的函数使用了成员的某些值,则您应该了解成员的初始化顺序。

关于c++ - 在初始化列表中调用私有(private)函数的情况下,它是未定义的行为吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2492318/

相关文章:

Java - 继承和构造函数错误

c++ - 推导函数返回类型的常量

c - 在 C 和 GCC 中使用带有返回参数的 pure/const 属性?

c++ - clang 和 g++ 在处理 const 对象时的差异

php - 从它自己的方法调用 PHP 构造函数

c++ - 这段代码将如何编译

c++ - 如何在 C++ 中将特征张量乘以另一个特征张量的标量和?

c++ - 为什么使用 std::vector<> 而不是 std::list<> 会导致代码大小增加?

c++ - 在 C 和 C++ 中调用函数时 EAX 寄存器的初始化差异

c++ - 绕过C++中的构造函数