In the below code the variable a
is no longer used after the call to xtransform
, is there some reason that it cannot be (or simply is not) implicitly converted to an rvalue reference at the time of that call?
#include <memory>
#include <algorithm>
#include <array>
template <typename O, typename I, size_t SZ, typename F>
auto xtransform(std::unique_ptr<std::array<I, SZ>>&& in, F&& func)
{
static_assert(
(sizeof(O)==sizeof(I)) &&
(alignof(O)==alignof(I)),
"Input and Output types are not compatible");
std::unique_ptr<std::array<O, SZ>> out {reinterpret_cast<std::array<O, SZ>*>(in->begin())};
std::transform(in->begin(), in->end(), out->begin(), func);
return out;
}
int main(void)
{
auto a = std::make_unique<std::array<long, 1000>>();
auto b = xtransform<double>(a, [](long in) { return double(in); }); // a has to be explicitly moved here
}
I was hoping to use the implicit conversion behavior to help the user out. In this case I was hoping the implicit conversion to an rvalue reference would work, but if the user continued to use the object (a
) after the call to xtransform
, the conversion wouldn't be allowed and it would fail to compile. This would protect the user from bugs caused by the memory reuse enabled by xtransform
. It would also informing the user of a need to copy, making expensive operations more explicit.