MST

星途 面试题库

面试题:C++ 类成员初始化效率优化之高级题

在C++中,一个类`ComplexClass`包含多个成员变量,其中有自定义类型`CustomType1`、`CustomType2`以及内置类型`int`和`double`。`CustomType1`和`CustomType2`的构造函数开销较大。请设计一个高效的构造函数,确保在初始化成员变量时尽可能减少不必要的构造和析构操作,说明设计思路并给出代码示例。
39.1万 热度难度
编程语言C++

知识考点

AI 面试

面试题答案

一键面试

设计思路

  1. 成员初始化列表:使用成员初始化列表来初始化成员变量,这样可以直接调用成员变量的构造函数进行初始化,避免先默认构造再赋值的额外开销。
  2. 参数传递:对于构造函数开销较大的自定义类型CustomType1CustomType2,尽量通过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) {
        // 构造函数体可以为空,所有初始化在初始化列表完成
    }
};