开发者

const boost::array<T,N> or boost::array<const T,N>?

What is difference between these two? Which one you would prefer when you need a fixed size array of cons开发者_如何学JAVAtant values?

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

Thanks.


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>.


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>.


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[].

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜