c++ - 非静态成员数组初始化的任何解决方法?

标签 c++

在 C++ 中,无法在初始化列表中初始化数组成员,因此成员对象应具有默认构造函数,并且应在构造函数中正确初始化。除了不使用数组之外,是否有任何(合理的)解决方法?

[在我们的应用程序中,任何可以仅使用初始化列表进行初始化的东西都比使用构造函数更可取,因为编译器和链接器可以分配和初始化数据,并且每个 CPU 时钟周期都很重要,甚至在 主要。但是,并非总是可以为每个类设置一个默认构造函数,此外,在构造函数中再次重新初始化数据反而违背了目的。]

例如我想要这样的东西(但是这个不行):

class OtherClass {
private:
    int data;
public:
    OtherClass(int i) : data(i) {}; // No default constructor!
};

class Foo {
private:
    OtherClass inst[3]; // Array size fixed and known ahead of time.
public:
    Foo(...)
        : inst[0](0), inst[1](1), inst[2](2)
        {};
};

我知道的唯一解决方法是非数组解决方法:

class Foo {
private:
    OtherClass inst0;
    OtherClass inst1;
    OtherClass inst2;
    OtherClass *inst[3];
public:
    Foo(...)
        : inst0(0), inst1(1), inst2(2) {
        inst[0]=&inst0;
        inst[1]=&inst1;
        inst[2]=&inst2;
    };
};

编辑:应该强调的是,OtherClass 没有默认构造函数,并且非常希望链接器能够分配所需的任何内存(一个或Foo 的更多静态实例将被创建),使用堆本质上是 verboten。我更新了上面的示例以突出显示第一点。

最佳答案

一种可能的解决方法是完全避免编译器调用 OtherClass 构造函数,并使用placement new 自行调用它,以任何您需要的方式对其进行初始化。示例:

  class Foo
  {
  private:
    char inst[3*sizeof(OtherClass)]; // Array size fixed. OtherClass has no default ctor.

    // use Inst to access, not inst
    OtherClass &Inst(int i) {return (OtherClass *)inst+i;}
    const OtherClass &Inst(int i) const {return (const OtherClass *)inst+i;}
  public:
    Foo(...)
    {
      new (Inst(0)) OtherClass(...);
      new (Inst(1)) OtherClass(...);
      new (Inst(2)) OtherClass(...);
    }
    ~Foo()
    {
      Inst(0)->~OtherClass();
      Inst(1)->~OtherClass();
      Inst(2)->~OtherClass();
    }
  };

为了满足 OtherClass 可能的对齐要求,如果在 VisualC++ 中工作,您可能需要使用 __declspec(align(x)),或者使用 char 以外的类型,例如:

Type inst[3*(sizeof(OtherClass)+sizeof(Type)-1)/sizeof(Type)];

...其中 Type 是 int、double、long long 或任何描述对齐要求的内容。

关于c++ - 非静态成员数组初始化的任何解决方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/120033/

相关文章:

c++ - 作为函数参数的模板结构

c++ - vector 中 bool 值的均匀分布

c++ - 我应该着手创建一个程序以将信息存储到文件中、编辑该文件中的信息并添加新信息的最佳方法是什么

c++ - C++中空字符串包含什么

链接器 hell 中的 C++ 新手

c++ - 如何模仿派生到基指针自动转换?

c++ - 我的句子回文代码(C++)有什么问题?

c++ - 用随机数初始化的对象

c++ - 在 RHEL 6 上强制核心转储

c++ - 静态内存使用的层次概述