gpt4 book ai didi

c++ - 可以使用成员函数来初始化初始化列表中的成员变量吗?

转载 作者:IT老高 更新时间:2023-10-28 12:37:29 24 4
gpt4 key购买 nike

好的,成员变量can be used初始化初始化列表中的其他成员变量(注意初始化顺序等)。成员函数呢?具体来说,根据 C++ 标准,此代码段是否合法?

struct foo{
foo(const size_t N) : N_(N), arr_(fill_arr(N)) {
//arr_ = fill_arr(N); // or should I fall back to this one?
}

std::vector<double> fill_arr(const size_t N){
std::vector<double> arr(N);
// fill in the vector somehow
return arr;
}

size_t N_;
std::vector<double> arr_;
// other stuff
};

最佳答案

是的,您在初始化列表中使用的成员函数是有效的并且符合标准。

数据成员按其声明的顺序进行初始化(这就是为什么它们应按其声明的顺序出现在初始化列表中的原因 - 您在示例中遵循的规则)。 N_ 首先初始化,您可以将此数据成员传递给 fill_arrfill_arr 在构造函数之前调用,但是因为这个函数不访问未初始化的数据成员(它根本不访问数据成员),所以它的调用被认为是安全的。

以下是 C++ 标准最新草案 (N3242=11-0012) 中的一些相关异常(exception):

§ 12.6.2.13: Member functions (including virtual member functions, 10.3) can be called for an object under construction.(...) 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. Example:

class A { public:    A(int); };

class B : public A {
int j;
public:
int f();
B() : A(f()), // undefined: calls member function
// but base A not yet initialized
j(f()) { } // well-defined: bases are all initialized
};

class C {
public:
C(int);
};

class D : public B, C {
int i;
public:
D() : C(f()), // undefined: calls member function
// but base C not yet initialized
i(f()) { } // well-defined: bases are all initialized
};

§12.7.1: For an object with a non-trivial constructor, referring to any non-static member or base class of the object before the constructor begins execution results in undefined behavior. Example

struct W { int j; };
struct X : public virtual W { };
struct Y {
int *p;
X x;
Y() : p(&x.j) { // undefined, x is not yet constructed
}
};

关于c++ - 可以使用成员函数来初始化初始化列表中的成员变量吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11174129/

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