本文介绍了初始化列表动态数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有可能给一个初始化列表的静态阵列的定义。例如:

It is possible to give an initializer list to the definition of a static array. Example:

int main()
{
  int int_static[2] = {1,2};
}

是一个类似的初始化列表可能一个动态数组?

Is a similar initializer list possible for a dynamic array?

int main()
{
  int* int_ptr = new int[2];
}

这是更接近我所试图做的:

This is closer to what I am trying to do:

struct foo
{
  foo(){}
  foo(void * ptr): ptr_(ptr) {}
  void * ptr_;
};

int main()
{
  foo* foo_ptr = new foo[10];
}

在初始化时不是默认的构造函数应该叫,但富:富(无效*)

At initialization time not the default constructor should be called, but foo:foo(void*).

具有用于动态数组的静态初始化列表的点可能出现用场的即时编译为加速器核心里面做只有一个可用的堆栈数量有限的情况下,但在同一时间,你构建你的与对象(加速器的编译时间=主机运行时)的静态初始化列表。

The point of having a static initializer list for a dynamic array might come handy in the case of Just-In-Time compilation for accelerator cores which do have only a limited amount of stack available, but at the same time you construct your objects with a (accelerator compile time = host run time) static initializer list.

我不认为(因为这需要编译器生成额外的code,即自变量的值复制到堆的位置)。我认为C ++ 0x中支持一些的,但我不能使用它。
现在,我可以使用这样的结构。也许有人知道一招。

I assume not (since this would require the compiler to generate additional code, namely to copy the values of the arguments to the heap location). I think c++0x supports some of this, but I cannot use it.Right now I could use such a construct. Maybe someone knows a trick..

最好的!

推荐答案

没有,你不能这样做。

No, you cannot do that.

我觉得C ++不允许这一点,因为让这样的事情不添加任何的不错的到了的功能的语言。换句话说,什么是点的动态的数组,如果你使用的静态的初始化初始化呢?

I think C++ doesn't allow this because allowing such thing doesn't add any nice-to-have feature to the language. In other words, what would be the point of dynamic array if you use a static initializer to initialize it?

动态数组的要点是在运行时创建一个大小 N 的数组,视实际需要。也就是说,code

The point of dynamic array is to create an array of size N which is known at runtime, depending on the actual need. That is, the code

int *p = new int[2];

意义不大对我来说比以下内容:

makes less sense to me than the following:

int *p = new int[N]; //N is known at runtime

如果是这样的话,那么你怎么能提供在静态的初始要素的数量,因为 N 不知道,直到运行时?

If that is so, then how can you provide the number of elements in the static initializer because N isn't known until runtime?

让我们假设,你可以写这样的:

Lets assume that you're allowed to write this:

int *p = new int[2] {10,20}; //pretend this!

但什么大的优势你得到写呢?没有。它的几乎的一样:

int a[] = {10,20};

当你被允许写为 N 元素阵列真正的好处是。但随后的问题是这样的:

The real advantage would be when you're allowed to write that for arrays of N elements. But then the problem is this:

 int *p = new int[N] {10,20, ... /*Oops, no idea how far we can go? N is not known!*/ };

这篇关于初始化列表动态数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 11:57
查看更多