C ++为什么非常量数组声明不好? [英] C++ Why are non-const array declarations bad?

查看:160
本文介绍了C ++为什么非常量数组声明不好?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有以下两个陈述:

If I have the two following statements:

// OK
const int ARRAYSIZE = 5;
int x[ARRAYSIZE];

// NOT OK
int ARRAYSIZEBAD = 5;
int y[ARRAYSIZEBAD];

而且我不使用-pedantic-errors标志进行编译...为什么第二个示例是一件坏事?在什么情况下最好与new运算符一起使用动态分配?

And I don't compile with the -pedantic-errors flag... why is the second example a bad thing? In what situation would it be preferable to use dynamic allocation with the new operator?

推荐答案

C ++为什么非常量数组声明不好?

C++ Why are non-const array declarations bad?

因为在编译时必须知道数组的长度.如果变量是非常量,则其值可能会在运行时更改,因此在编译时将不知道.只能将编译时常数表达式用作数组的长度-因此,只有在观察到其初始化程序之后,才能将const变量用作数组的长度.

Because the length of the array must be known at the time of compilation. If a variable is non-const, then its value could change at run time, and thus would not be known at compile time. Only a compile time constant expression can be used as the length of an array - thus a const variable can only be used as the length of an array after its initialiser has been observed.

int[ARRAYSIZE]是一种类型.在编译时知道大小的要求扩展到了实例化的所有类型,而不仅仅是数组类型.

int[ARRAYSIZE] is a type. The requirement that size is known at compile time extends to all types that you instantiate, not just array types.

在什么情况下最好使用动态分配...

In what situation would it be preferable to use dynamic allocation ...

在编译时不知道数组的长度时,需要动态分配.

You need dynamic allocation when you don't know the length of the array at compile time.

当数组很大时,您还需要非自动分配.这是因为为自动分配保留的内存通常非常有限.

You also need non-automatic allocation when the array is big. This is because the memory reserved for automatic allocation is often quite limited.

...使用新的运算符?

... with the new operator?

使用new表达式分配动态内存很少是可取的. std::vector通常在需要动态数组时使用.

It's rarely preferable to allocate dynamic memory using a new-expression. std::vector is typically used when dynamic array is needed.

这篇关于C ++为什么非常量数组声明不好?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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