I have a function that accepts a const reference to a valarray, and I want to be able to slice the array and pass the slice into another function that expects a const slice_array. I know that I can just use operator[] and a slice to get a new, copied valarray out of the original valarray, but I want to avoid the copy. Everything is const, so I feel like that should be okay. However, the documentation for the subscript operator for valarray ONLY returns a slice_array objects when applied to non-const valarrays. This feels kind of a major deficiency in the valarray class. Am I missing something? How do I get a slice of a const valarray without incurring a copy?
Here is an example of what I'm talking about:
void foo( const valarray<double> &big_stuff )
{
const slice_array<double> small_stuff = big_stuff[slice(start, size, stride)];
bar( small_stuff );
}
Thanks!
How do I get a slice of a const valarray without incurring a copy?
There is no way to do this, because of std::valarray not contain std::slice_array
for any request, so it cat not give you just link(pointer,reference) to std::slice_array that you request.
But std::slice_array can contains only three machine words,
hard to imagine situation where not copy of std::slice_array can optimize something. For example from gcc/libstdc++ (only data, functions stripped):
template<typename _Tp>
class slice_array {
const size_t _M_sz;
const size_t _M_stride;
const _Array<_Tp> _M_array;
};
where _Array:
template<typename _Tp>
struct _Array { _Tp* const __restrict__ _M_data; };
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With