ukoethe / vigra

a generic C++ library for image analysis
http://ukoethe.github.io/vigra/
Other
409 stars 191 forks source link

Why does bind() return a mutable view of an immutable MultiArray? #452

Closed emmenlau closed 2 years ago

emmenlau commented 5 years ago

I just found a behavior that puzzles me a bit. The following code seems to be legal:

const vigra::MultiArray<2, double> vArray(vigra::Shape2(100, 100));
vigra::MultiArrayView<1, double> vArrayView = vArray.bindOuter(17);
vArrayView = 42.0;

The signature of bindOuter is:

MultiArrayView<N-1, T, StrideTag> bindOuter(difference_type_1 d) const;

Isn't this slighly unintuitive that the view may modify the const MultiArray? Is there a reason to make it like this?

ukoethe commented 5 years ago

Yes, this is a bit unintuitive, but not so easy to fix. The signature should be

MultiArrayView<N-1, std::add_const_t<T>, StrideTag> bindOuter(difference_type_1 d) const;

but this requires all array types to properly deal with T being a const type. Note that a return type like MultiArrayView<N-1, T, StrideTag> const would not improve things, because the const can be casted away easily. I got it right in my xvigra experiment (so it can be done :-), but found the issue not pressing enough for a large rewrite of the existing code. The current solution was also much simpler and more convenient before the auto keyword was added to the language.

emmenlau commented 2 years ago

I guess this can be closed now.