在初始化数组构造函数不使用默认的构造函数或赋值 [英] Initialize array in constructor without using default constructor or assignment

查看:187
本文介绍了在初始化数组构造函数不使用默认的构造函数或赋值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑:

struct A {

 A (int);

 A (const A &);
};

struct B {

 A foo [2];

 B (const A & x, const A & y)
 : foo {x, y} /* HERE IS THE PROBLEM */
 {}
};

我期待这一点,因为我用的C ++ 0x在GCC4.3,据称支持初始化器列表的支持工作。没有喜悦。

I was expecting this to work since I'm using C++0x support in GCC4.3, which allegedly supports initialiser lists. No joy.

我有没有默认构造函数A类。这是没有商量余地。分配默认后是不是一种选择。

I have a class A which has no default constructor. This is not negotiable. Assignment post-default is not an option.

我想创建B上使用A. B :: foo的可能不标准::向量。

I am trying to create B which uses A. B::foo may not be std::vector.

我怎么能初始化 B :: foo的 B(...),构建它的元素恰好一次?

How can I initialise B::foo in B(...), constructing its elements exactly once?

目前,我condidering计算机来代替乙

At the moment, I am condidering replacing B with

struct B {

A foo_a;

B foo_b;

A * foo () {
assert ((&foo_b) - *&foo_a) == 1);
return &foo_a;
}

B (const A & x, const A & y) : foo_a(x), foo_b(y) {}
};

甚至使用字符富[2 * sizeof的(A)] 与安置新 - !YUK

Or even using char foo [2*sizeof(A)] with placement new -- YUK!

肯定有这样做一个适当的方式?

Surely there's a proper way to do this?

推荐答案

不幸的是,实在是没有合适的,干净的方式做到这一点。考虑它的东西的语言的限制,从C ++的构造函数和C风格的数组一个尴尬的混合效果。在C ++ 11标准的解决这个问题,但在那之前你必须解决一个解决方法。

Unfortunately, there really is no proper, clean way to do this. Consider it something of a language limitation that results from an awkward mixing of C++ constructors and C style arrays. The C++11 standard addresses this issue, but until then you'll have to settle for a workaround.

由于 A 没有默认的构造函数,一个可能的解决方法是让 A * 指针数组,然后循环阵列上并初始化每一个与。 (显然,别忘了删除 B中的析构函数数组中的每个项目,或者只是使用智能指针。)

Since A has no default constructor, one possible work-around is to have an array of A* pointers, and then loop over the array and initialize each one with new. (Obviously, don't forget to delete each item in the array in B's destructor, or just use smart pointers.)

这篇关于在初始化数组构造函数不使用默认的构造函数或赋值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆