const boost::array;或 boost::array

发布于 2024-10-31 20:47:36 字数 169 浏览 1 评论 0原文

这两者有什么区别?当您需要固定大小的常量值数组时,您会更喜欢哪一个?

const boost::array<int, 2> x = {0, 1};
boost::array<const int, 2> y = {0, 1};

谢谢。

What is difference between these two? Which one you would prefer when you need a fixed size array of constant values?

const boost::array<int, 2> x = {0, 1};
boost::array<const int, 2> y = {0, 1};

Thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

℡寂寞咖啡 2024-11-07 20:47:36

第二个将阻止您将其复制到新的非常量数组,

boost::array<const int, 2> y = {0, 1};
boost::array<int, 2> y1 = y; // error!

因为我希望它能工作,所以我可能会选择第一个选项。将第二个参数传递给需要 boost::array 的模板将阻止这些模板修改其参数(即使它是一个副本)。第一个将“正常工作”,因为参数的类型为 boost::array

The second one will prevent that you copy it to a new non-const array

boost::array<const int, 2> y = {0, 1};
boost::array<int, 2> y1 = y; // error!

Since I would expect that to work, I would probably go with the first option. Passing the second one to templates that expect a boost::array<T, N> will prevent those templates from modifying their parameter (even if it's a copy). The first one would "just work", since the parameter would have the type boost::array<int, 2>.

掩饰不了的爱 2024-11-07 20:47:36

这确实是风格上的差异。

如果您尝试对 const 数组 调用 assign,编译器错误会提示没有匹配的函数。如果您对array执行相同的操作,它会指向assign内部的无效操作。

我认为 const array 能更好地表达意图,并且看起来更像相应的 C 风格数组声明。但我不会努力改变一些事情,例如在遗留代码中或在可能生成 array 的模板中。

It's really a stylistic difference.

If you try to call assign on a const array, the compiler error says there is no matching function. If you do the same with an array<const T>, it points at the invalid operation inside assign.

I think const array expresses intent better, and looks more like the corresponding C-style array declaration. But I wouldn't make an effort to change things, for example in legacy code or inside a template which might generate an array<const T>.

于我来说 2024-11-07 20:47:36

在这种情况下,const intint 几乎是相同的。对 array 无法执行的操作,与对 array 执行的操作一样。如果你有一些类而不是int,那么就会有区别。使用 array 您将无法对数组的元素调用非常量方法。
const array 更强大,因为您无法修改任何内容。您不能调用元素的非常量方法并且您不能通过替换元素来更改数组本身,例如使用operator[]

A const int and an int in this context are pretty much the same. There's nothing you can do to an array<int,2> that you can't do to an array<const int, 2>. If instead of int you have some class then there would be a difference. with array<const MyClass, 2> you would not be able to call non-const methods on the elements of the array.
const array<MyClass, 2> is stronger in that you cannot modify anything what so ever. You can't call non-const methods of the elements and you can't change the array itself by replacing the elements, say using operator[].

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文