设计思路
- 成员初始化列表:使用成员初始化列表来初始化成员变量,这样可以直接调用成员变量的构造函数进行初始化,避免先默认构造再赋值的额外开销。
- 参数传递:对于构造函数开销较大的自定义类型
CustomType1
和CustomType2
,尽量通过const
引用传递参数,以减少临时对象的创建。
代码示例
class CustomType1 {
public:
CustomType1(int value) {
// 模拟较大开销的构造函数操作
for (int i = 0; i < 1000000; ++i) {
// 一些复杂计算
}
}
};
class CustomType2 {
public:
CustomType2(double value) {
// 模拟较大开销的构造函数操作
for (int i = 0; i < 1000000; ++i) {
// 一些复杂计算
}
}
};
class ComplexClass {
private:
CustomType1 custom1;
CustomType2 custom2;
int intValue;
double doubleValue;
public:
ComplexClass(const CustomType1& c1, const CustomType2& c2, int i, double d)
: custom1(c1), custom2(c2), intValue(i), doubleValue(d) {
// 构造函数体可以为空,所有初始化在初始化列表完成
}
};