在C++中,无法在初始化列表中初始化数组成员,因此成员对象应该具有默认构造函数,并且应该在构造函数中正确初始化它们.除了不使用数组之外,还有(合理的)解决方法吗?
[任何可以使用初始化列表初始化的东西在我们的应用程序中远比使用构造函数更好,因为这些数据可以由编译器和链接器分配和初始化,并且每个CPU时钟周期都很重要,甚至在此之前main
.但是,并不总是可以为每个类都有一个默认的构造函数,而且,在构造函数中再次重新初始化数据反而无法实现目的.]
例如,我想要这样的东西(但这个不起作用):
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)
{};
};
Run Code Online (Sandbox Code Playgroud)
我所知道的唯一解决方法是非阵列的:
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;
};
};
Run Code Online (Sandbox Code Playgroud)
编辑:应该强调的是OtherClass
,没有默认构造函数,并且非常希望链接器能够分配所需的任何内存(Foo
将创建一个或多个静态实例),使用堆基本上是禁止的.我已经更新了上面的例子,以突出第一点.
一种可能的解决方法是完全避免编译器调用 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();
}
};
Run Code Online (Sandbox Code Playgroud)
为了满足 OtherClass 可能的对齐要求,如果在 VisualC++ 中工作,您可能需要使用 __declspec(align(x)),或者使用 char 以外的类型,例如:
Type inst[3*(sizeof(OtherClass)+sizeof(Type)-1)/sizeof(Type)];
Run Code Online (Sandbox Code Playgroud)
...其中 Type 是 int、double、long long 或任何描述对齐要求的内容。
归档时间: |
|
查看次数: |
7325 次 |
最近记录: |