首页 > 解决方案 > 从左值到右值引用的隐式转换何时发生?

问题描述

在下面的代码中,变量a在调用之后不再使用xtransform,是否有某种原因在调用时它不能(或根本不是)隐式转换为右值引用?

#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
}

我希望使用隐式转换行为来帮助用户。在这种情况下,我希望隐式转换为右值引用会起作用,但如果用户在调用 后继续使用对象 ( a) xtransform,则不允许转换并且编译失败。这将保护用户免受由xtransform. 它还将通知用户需要复制,使昂贵的操作更加明确。

标签: c++move-semantics

解决方案


推荐阅读