在 C++ 中,未在成员初始化列表中构造的类的任何成员在执行包含类的构造函数之前默认构造。但是,如果该成员变量无论如何都要在它所在的类的构造函数中构造,这似乎是非常浪费的。
我在下面提供了一个示例来阐明我的意思。在这里,Example
该类有一个x
类型为 的成员变量LargeIntimidatingClass
。使用成员初始化列表(中的第一个构造函数Example
)x
只构造一次。但是,如果x
不能使用成员初始化列表合理构造,它会被构造两次!
//This class used as part of the example class further below
class LargeIntimidatingClass {
// ...
//many member variables and functions
// ...
LargeIntimidatingClass() {
//Painfully expensive default initializer
}
LargeIntimidatingClass(int a, double b) {
//Complicated calculations involving a and b
}
};
//Here, this class has a LargeIntimidatingClass as a member variable.
class Example {
LargeIntimidatingClass x;
char c;
//Basic member initialization list constructor. Efficient!
Example(int a, double b, char c) : x(a,b), c(c) {}
//What if the parameters to the LargeIntimidatingClass's constructor
//need to be computed inside the Example's constructor beforehand?
Example(std::string sophisticatedArgument) {
//Oh no! x has already been default initialized (unnecessarily!)
int a = something1(sophisticatedArgument);
double b = something2(sophisticatedArgument);
//x gets constructed again! Previous (default) x is totally wasted!
x = LargeIntimidatingClass(a,b);
c = something3(sophisticatedArgument);
}
};
是的,我意识到在这个愚蠢的示例中您可以编写Example(string s) : x(f1(s),f2(s)), c(f3(s)) {}
,但我相信您可以想象将一堆逻辑推入成员初始化列表的情况很麻烦(甚至是不可能的)。
当成员初始化列表中未列出成员变量的默认构造函数时,是否可以禁用它?