c++ - 从左值到右值引用的隐式转换何时发生?
问题描述
在下面的代码中,变量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
. 它还将通知用户需要复制,使昂贵的操作更加明确。
解决方案
推荐阅读
- javascript - 如何使用 Angular cli 默认空运行
- java - 多模块maven项目:无法在项目上执行目标,无法解析项目的依赖关系,找不到工件
- powershell - 使用 Powershell 查询 (AD) 的成员
- mongodb - Perseo fe docker 实例无法启动
- perl - 在 perl 中更新哈希键时,不能在“严格引用”时使用字符串作为哈希引用?
- android - 如何从适配器调用片段?在 getFragmentManager 处出错
- pdf - 附加 NULNULNULNUL%PDF-1.6 的 PDF 标题
- webcam - USB 网络摄像头未确认为 AVMediaTypeVideo - XCode/Mac
- c# - 从相同格式的字符串中获取时间
- javascript - Knex:嵌套原始查询,转义“?” 特点