1

在 C++ 中,在成员初始化列表中构造的类的任何成员在执行包含类的构造函数之前默认构造。但是,如果该成员变量无论如何都要在它所在的类的构造函数中构造,这似乎是非常浪费的。

我在下面提供了一个示例来阐明我的意思。在这里,Example该类有一个x类型为 的成员变量LargeIntimidatingClass。使用成员初始化列表(中的第一个构造函数Examplex只构造一次。但是,如果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)) {},但我相信您可以想象将一堆逻辑推入成员初始化列表的情况很麻烦(甚至是不可能的)。

当成员初始化列表中未列出成员变量的默认构造函数时,是否可以禁用它?

4

3 回答 3

3

您不能禁用构造。在到达构造函数的主体之前,必须初始化所有类成员。也就是说,您可以轻松解决该问题。您可以添加一个私有静态成员函数,该函数从中获取并a返回baLargeIntimidatingClass

class Example {
    LargeIntimidatingClass x;
    char c;
    static LargeIntimidatingClass make_LargeIntimidatingClass(std::string sophisticatedArgument)
    {
        int a = something1(sophisticatedArgument);
        double b = something2(sophisticatedArgument);
        return LargeIntimidatingClass(a,b);
    }
    static char make_c(std::string sophisticatedArgument)
    {
        return something3(sophisticatedArgument);
    }
public:

    //Basic member initialization list constructor. Efficient!
    Example(int a, double b, char c) : x(a,b), c(c) {}

    // now we use helpers to initialize in the member initialization list
    Example(std::string sophisticatedArgument) : x(make_LargeIntimidatingClass(sophisticatedArgument), c(make_c(sophisticatedArgument) {
        //now everything is initialized correctly
    }
};
于 2018-12-28T18:32:35.973 回答
1

禁用语言工作方式的一个组成部分?不,但是您可以重构以使用该语言,或者以各种方式绕过它。

  1. 有一个指向扩展类的(智能)指针成员。
  2. 让成员成为std:aligned_storage并通过放置新创建对象。然后自己仔细管理对象的生命周期。
  3. 持有一个std:optional。管理初始化并让库类型管理其余部分,以减少对象大小的一些开销。
于 2018-12-28T18:26:01.660 回答
0

当成员初始化列表中未列出成员变量的默认构造函数时,是否可以禁用它?

不,那是不可能的。

于 2018-12-28T18:17:53.313 回答