C++ 在构造函数初始化程序中初始化成员数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4057948/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 14:24:01  来源:igfitidea点击:

Initializing a member array in constructor initializer

c++c++11initializer-listctor-initializeraggregate-initialization

提问by Armen Tsirunyan

class C 
{
public:
 C() : arr({1,2,3}) //doesn't compile
{}
    /*
    C() : arr{1,2,3} //doesn't compile either
{}
    */
private:
 int arr[3];
};

I believe the reason is that arrays can be initialized only with =syntax, that is:

我相信原因是数组只能用=语法初始化,即:

int arr[3] = {1,3,4};

Questions

问题

  1. How can I do what I want to do (that is, initializean array in a constructor (not assigning elements in the body)). Is it even possible?
  2. Does the C++03 standard say anything special about initializing aggregates (including arrays) in ctor initializers? Or the invalidness of the above code is a corollary of some other rules?
  3. Do C++0x initializer lists solve the problem?
  1. 我该如何做我想做的事情(即在构造函数中初始化一个数组(而不是在主体中分配元素))。甚至有可能吗?
  2. C++03 标准对在 ctor 初始值设定项中初始化聚合(包括数组)有什么特别说明吗?或者上面代码的无效是其他一些规则的必然结果?
  3. C++0x 初始化列表能解决问题吗?

P.S.Please do not mention vectors, boost::arrays, and their superiority to arrays, which I am well aware of.

PS请不要提及向量、boost::arrays 以及它们对数组的优越性,我很清楚这一点。

采纳答案by Johannes Schaub - litb

  1. How can I do what I want to do (that is, initialize an array in a constructor (not assigning elements in the body)). Is it even possible?
  1. 我该如何做我想做的事情(即在构造函数中初始化一个数组(而不是在主体中分配元素))。甚至有可能吗?

Yes. It's using a struct that contains an array. You say you already know about that, but then I don't understand the question. That way, you doinitialize an array in the constructor, without assignments in the body. This is what boost::arraydoes.

是的。它使用一个包含数组的结构。你说你已经知道了,但我不明白这个问题。这样,您可以在构造函数中初始化一个数组,而无需在主体中进行赋值。这就是boost::array它的作用。

Does the C++03 standard say anything special about initializing aggregates (including arrays) in ctor initializers? Or the invalidness of the above code is a corollary of some other rules?

C++03 标准对在 ctor 初始值设定项中初始化聚合(包括数组)有什么特别说明吗?或者上面代码的无效是其他一些规则的必然结果?

A mem-initializer uses direct initialization. And the rules of clause 8 forbid this kind of thing. I'm not exactly sure about the following case, but some compilers do allow it.

内存初始化程序使用直接初始化。而第 8 条的规则禁止这种事情。我不确定以下情况,但有些编译器确实允许这样做。

struct A {
  char foo[6];
  A():foo("hello") { } /* valid? */
};

See this GCC PRfor further details.

有关更多详细信息,请参阅此 GCC PR

Do C++0x initializer lists solve the problem?

C++0x 初始化列表能解决问题吗?

Yes, they do. However your syntax is invalid, I think. You have to use braces directly to fire off list initialization

是的,他们这样做。但是,我认为您的语法无效。您必须直接使用大括号来触发列表初始化

struct A {
  int foo[3];
  A():foo{1, 2, 3} { }
  A():foo({1, 2, 3}) { } /* invalid */
};

回答by Cheers and hth. - Alf

C++98 doesn't provide a direct syntax for anything but zeroing (or for non-POD elements, value-initializing) the array. For that you just write C(): arr() {}.

C++98 不提供任何直接的语法,只是将数组归零(或对于非 POD 元素,值初始化)。为此,您只需编写C(): arr() {}.

I thing Roger Pate is wrong about the alleged limitations of C++0x aggregate initialization, but I'm too lazy to look it up or check it out, and it doesn't matter, does it? EDIT: Roger was talking about "C++03", I misread it as "C++0x". Sorry, Roger. ?

我认为 Roger Pate 关于 C++0x 聚合初始化的所谓限制是错误的,但我懒得查找或检查它,这无关紧要,是吗?编辑:Roger 在谈论“C++03”,我误读了它为“C++0x”。对不起,罗杰。?

A C++98 workaround for your current code is to wrap the array in a structand initialize it from a static constant of that type. The data has to reside somewhere anyway. Off the cuff it can look like this:

当前代码的 C++98 解决方法是将数组包装在 a 中struct,并从该类型的静态常量对其进行初始化。无论如何,数据必须驻留在某处。从袖口上看,它可能是这样的:

class C 
{
public:
    C() : arr( arrData ) {}

private:
     struct Arr{ int elem[3]; };
     Arr arr;
     static Arr const arrData;
};

C::Arr const C::arrData = {{1, 2, 3}};

回答by Alexey Malistov

Workaround:

解决方法:

template<class T, size_t N>
struct simple_array { // like std::array in C++0x
   T arr[N];
};


class C : private simple_array<int, 3> 
{
      static simple_array<int, 3> myarr() {
           simple_array<int, 3> arr = {1,2,3};
           return arr;
      }
public:
      C() : simple_array<int, 3>(myarr()) {}
};

回答by Alexey Malistov

  1. No, unfortunately.
  2. You just can't in the way you want, as it's not allowed by the grammar (more below). You can only use ctor-like initialization, and, as you know, that's not available for initializing each item in arrays.
  3. I believe so, as they generalize initialization across the board in many useful ways. But I'm not sure on the details.
  1. 不,不幸的是。
  2. 你只是不能以你想要的方式,因为语法不允许(更多见下文)。您只能使用类似 ctor 的初始化,而且如您所知,这不能用于初始化数组中的每个项目。
  3. 我相信是这样,因为他们以许多有用的方式全面概括了初始化。但我不确定细节。

In C++03, aggregate initialization only applies with syntax similar as below, which must be a separate statement and doesn't fit in a ctor initializer.

在 C++03 中,聚合初始化只适用于类似下面的语法,它必须是一个单独的语句,不适合 ctor 初始化程序。

T var = {...};

回答by eold

How about

怎么样

...
  C() : arr{ {1,2,3} }
{}
...

?

?

Compiles fine on g++ 4.8

在 g++ 4.8 上编译良好

回答by DaveEff

You want to init an array of ints in your constructor? Point it to a static array.

您想在构造函数中初始化一个整数数组吗?将其指向一个静态数组。

class C 
{
public:
    int *cArray;

};

C::C {
    static int c_init[]{1,2,3};
    cArray = c_init;
}