![](/img/trans.png)
[英]Can member variables be used to initialize other members in an initialization list?
[英]can member functions be used to initialize member variables in an initialization list?
可以,成员变量可用于初始化初始化列表中的其他成员变量(注意初始化顺序等)。 成员函数呢? 具体来说,根据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_arr
。 fill_arr
在构造函数之前被调用,但是因为此函数不访问未初始化的数据成员(它根本不访问数据成员),所以认为它的调用是安全的。
以下是C ++标准的最新草案(N3242 = 11-0012)中的一些相关内容:
第12.6.2.13节:可以为正在构造的对象调用成员函数(包括虚拟成员函数10.3)。(...)但是,如果这些操作是在ctor初始化程序(或直接或间接调用的函数)中执行的,则在所有用于基类的mem-initializers完成之前,从ctor-initializer中获取),操作结果是不确定的。 例:
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节:对于具有非平凡构造函数的对象,在构造函数开始执行之前引用该对象的任何非静态成员或基类都会导致未定义的行为。 例
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
}
};
在初始化列表中初始化对象时,该对象尚未完全构造。
如果那些函数试图访问尚未构造的对象部分,则这是未定义的行为,否则会很好。
看到这个答案 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.