gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:06:15 25 4
gpt4 key购买 nike

考虑以下代码:

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com