const boost::array;或 boost::array?
这两者有什么区别?当您需要固定大小的常量值数组时,您会更喜欢哪一个?
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
第二个将阻止您将其复制到新的非常量数组,
因为我希望它能工作,所以我可能会选择第一个选项。将第二个参数传递给需要
boost::array
的模板将阻止这些模板修改其参数(即使它是一个副本)。第一个将“正常工作”,因为参数的类型为boost::array
。The second one will prevent that you copy it to a new non-const array
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 typeboost::array<int, 2>
.这确实是风格上的差异。
如果您尝试对
const 数组
调用assign
,编译器错误会提示没有匹配的函数。如果您对array
执行相同的操作,它会指向assign
内部的无效操作。我认为 const array 能更好地表达意图,并且看起来更像相应的 C 风格数组声明。但我不会努力改变一些事情,例如在遗留代码中或在可能生成
array
的模板中。It's really a stylistic difference.
If you try to call
assign
on aconst array
, the compiler error says there is no matching function. If you do the same with anarray<const T>
, it points at the invalid operation insideassign
.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 anarray<const T>
.在这种情况下,
const int
和int
几乎是相同的。对array
无法执行的操作,与对array
执行的操作一样。如果你有一些类而不是int
,那么就会有区别。使用array
您将无法对数组的元素调用非常量方法。const array
更强大,因为您无法修改任何内容。您不能调用元素的非常量方法并且您不能通过替换元素来更改数组本身,例如使用operator[]
。A
const int
and anint
in this context are pretty much the same. There's nothing you can do to anarray<int,2>
that you can't do to anarray<const int, 2>
. If instead ofint
you have some class then there would be a difference. witharray<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 usingoperator[]
.