C++ 在构造函数初始值设定项中确定数组大小

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/751878/
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-27 17:05:54  来源:igfitidea点击:

Determine array size in constructor initializer

c++arraysconstructorinitialization

提问by zaratustra

In the code below I would like array to be defined as an array of size x when the Class constructor is called. How can I do that?

在下面的代码中,我希望在调用 Class 构造函数时将数组定义为大小为 x 的数组。我怎样才能做到这一点?

class Class
{
public:
  int array[];
  Class(int x) : ??? { }
}

回答by Jeff Diamond

You folks have so overcomplicated this. Of course you can do this in C++. It is fine for him to use a normal array for efficiency. A vector only makes sense if he doesn't know the final size of the array ahead of time, i.e., it needs to grow over time.

你们把事情想得太复杂了。当然,你可以在 C++ 中做到这一点。为了效率,他使用普通数组是没问题的。一个向量只有在他提前不知道数组的最终大小时才有意义,即它需要随着时间的推移而增长。

If you can know the array size one level higher in the chain, a templated class is the easiest, because there's no dynamic allocation and no chance of memory leaks:

如果你能知道链中更高一级的数组大小,模板类是最简单的,因为没有动态分配,也没有内存泄漏的机会:

template < int ARRAY_LEN > // you can even set to a default value here of C++'11

class MyClass
  {   
  int array[ARRAY_LEN]; // Don't need to alloc or dealloc in structure!  Works like you imagine!   
  }

// Then you set the length of each object where you declare the object, e.g.

MyClass<1024> instance; // But only works for constant values, i.e. known to compiler

If you can't know the length at the place you declare the object, or if you want to reuse the same object with different lengths, or you must accept an unknown length, then you need to allocate it in your constructor and free it in your destructor... (and in theory always check to make sure it worked...)

如果你在声明对象的地方不知道长度,或者你想重用不同长度的同一个对象,或者你必须接受一个未知的长度,那么你需要在你的构造函数中分配它并释放它你的析构函数......(理论上总是检查以确保它有效......)

class MyClass
  {
  int *array;

  MyClass(int len) { array = calloc(sizeof(int), len); assert(array); }   
  ~MyClass() { free(array); array = NULL; } // DON'T FORGET TO FREE UP SPACE!
  }

回答by C?t?lin Piti?

You can't initialize the size of an array with a non-const dimension that can't be calculated at compile time (at least not in current C++ standard, AFAIK).

您不能使用在编译时无法计算的非常量维度来初始化数组的大小(至少在当前的 C++ 标准 AFAIK 中不是这样)。

I recommend using std::vector<int>instead of array. It provides array like syntax for most of the operations.

我建议使用std::vector<int>而不是数组。它为大多数操作提供类似数组的语法。

回答by John Dibling

Use the new operator:

使用新运算符:

class Class
{
   int* array;
   Class(int x) : array(new int[x]) {};
};

回答by AFoglia

I don't think it can be done. At least not the way you want. You can't create a statically sized array (array[]) when the size comes from dynamic information (x).

我不认为这是可以做到的。至少不是你想要的方式。当大小来自动态信息 (x) 时,您无法创建静态大小的数组 (array[])。

You'll need to either store a pointer-to-int, and the size, and overload the copy constructor, assignment operator, and destructor to handle it, or use std::vector.

您需要存储指向 int 的指针和大小,并重载复制构造函数、赋值运算符和析构函数来处理它,或者使用 std::vector。

class Class
{
  ::std::vector<int> array;
  Class(int x) : array(x) { }
};

回答by Miguel Enrique León Figueras

Don't you understand there is not need to use vector, if one wants to use arrays it's a matter of efficiency, e.g. less space, no copy time (in such case if handled properly there is not even need to delete the array within a destructor), etc. wichever reasons one has.

难道你不明白没有必要使用向量,如果你想使用数组,这是一个效率问题,例如更少的空间,没有复制时间(在这种情况下,如果处理得当,甚至不需要在一个数组中删除数组)析构函数)等,无论出于何种原因。

the correct answer is: (quoted)

正确答案是:(引用)

class Class
{
   int* array;
   Class(int x) : array(new int[x]) {};
};

Do not try to force one to use non optimal alternatives or you'll be confusing unexperienced programmers

不要试图强迫一个人使用非最佳的替代方案,否则你会让没有经验的程序员感到困惑

回答by user563910

Sorry for necroing this old thread. There is actually a way to find out the size of the array compile-time. It goes something like this:

很抱歉破坏了这个旧线程。实际上有一种方法可以在编译时找出数组的大小。它是这样的:

#include <cstdlib>

template<typename T>
    class Class
    {
        T* _Buffer;

        public:
        template<size_t SIZE>
            Class(T (&static_array)[SIZE])
            {
                _Buffer = (T*)malloc(sizeof(T) * SIZE);

                memcpy(_Buffer, static_array, sizeof(T) * SIZE);
            }

            ~Class()
            {
                if(_Buffer)
                {
                    free(_Buffer);
                    _Buffer = NULL;
                }
            }
    };

int main()
{
    int int_array[32];
    Class<int> c = Class<int>(int_array);

    return 0;
}

Alternatively, if you hate to malloc / new, then you can create a size templated class instead. Though, I wouldn't really recommend it and the syntax is quite ugly.

或者,如果您讨厌 malloc / new,那么您可以创建一个大小模板类。虽然,我不会真正推荐它,而且语法非常难看。

#include <cstdio>

template<typename T, size_t SIZE>
    class Class
    {
        private:
            T _Array[sz];
        public:
            Class(T (&static_array)[SIZE])
            {
                memcpy(_Array, static_array, sizeof(T) * SIZE);
            }
    };

int main()
{
    char int_array[32];
    Class<char, sizeof(int_array)> c = Class<char, sizeof(int_array)>(int_array);
    return 0;
}

Anyways, I hope this was helpful :)

无论如何,我希望这是有帮助的:)

回答by JaredPar

Instead of using a raw array, why not use a vector instead.

与其使用原始数组,不如使用向量。

class SomeType {
  vector<int> v;
  SomeType(size_t x): v(x) {}
};

Using a vector will give you automatic leak protection in the face of an exception and many other benefits over a raw array.

使用向量将为您提供面对异常时的自动泄漏保护以及与原始数组相比的许多其他好处。

回答by JaredPar

You can't do it in C++ - use a std::vector instead:

你不能在 C++ 中做到这一点 - 使用 std::vector 代替:

#include <vector>

struct A {
   std::vector <int> vec; 
   A( int size ) : vec( size ) {
   }
};

回答by Shree

Declare your array as a pointer. You can initialize it in the initializer list later through through new.

将数组声明为指针。您可以稍后通过 new 在初始化列表中对其进行初始化。

Better to use vector for unknown size.

最好对未知大小使用向量。

You might want to look at this questionas well on variable length arrays.

您可能还想在可变长度数组上查看此问题

回答by Martin York

Two options:

两种选择:

Use std::vector. This allows easy re-sizing of the array.
Use std::tr1::array. This has a static size.

使用 std::vector。这允许轻松地重新调整阵列的大小。
使用 std::tr1::array。这具有静态大小。

Both can be correctly initialized in the constructors initializer list.

两者都可以在构造函数初始化列表中正确初始化。