常数数组 [英] constant arrays

查看:130
本文介绍了常数数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个很好的旧C数组:

This is a good old C array:

int a[10];

这是一个很好的旧C数组,它是const:

And this is a good old C array that is const:

const int b[10];

在C ++中,似乎有两种方法来定义conststd::array:

In C++, there seem to be two ways to define std::arrays that are const:

std::array<const int, 10> c;
const std::array<int, 10> d;

这两个定义是否相等?如果是这样,什么是惯用的?如果没有,有什么区别?

Are these two definitions equivalent? If so, what is the idiomatic one? If not, what are the differences?

推荐答案

好吧,原始的const int b[10];仅在可以初始化数组时才有用,因此两个std::array示例在实践中均不起作用.

Well, the original const int b[10]; is only useful when you can initialize the array, so both of the std::array examples don't work in practice.

std::array<const int, 10> c;

这是与const int c[10];最接近的.问题在于将没有默认构造函数,并且由于元素不是可变的,因此使用它毫无用处.您必须在构造函数中为其提供一些初始化.照原样,由于默认构造函数未初始化元素,因此将产生编译器错误.

This is the closest to const int c[10];. The problem is there will be no default constructor for it, and because the elements are not mutable, it's worthless to use this. You must provide some initialization for it in the constructor. As-is, it will give a compiler error because the default constructor did not initialize the elements.

此代码表示c是可变的,但元素本身不是可变的.但是实际上,在c上没有不影响元素的突变.

This code means that c is mutable, but the elements themselves are not. In practice, however, there are no mutations on c that don't affect the elements.

const std::array<int, 10> d;

这意味着d不是可变的,但是元素是可变的int类型.因为const会传播到成员,所以这意味着元素仍然不能被调用方更改.与上面的示例类似,您将需要初始化d,因为它是const.

This means d is not mutable, but the elements are of mutable type int. Because const will propagate to the members, it means the elements are still not mutable by the caller. Similar to the above example, you will need to initialize d because it's const.

在实践中,它们在可变性方面的行为都相似,因为对array进行的可变操作始终会触及元素.

In practice, they will both behave similarly with respect to mutability, because mutable operations on array always touch the elements.

这篇关于常数数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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