为什么将临时对象作为参数传递需要 std::move?
Why does passing a temporary object as an argument need std::move?
我正在尝试通过初始值设定项列表将字符串文本数组传递给仅接受const char**
的函数。示例代码如下:
// Example program
void foo(const char **) { }
int main() {
using argType = const char*[];
foo(argType{"a","b"});
}
这不会在 GCC 中编译。错误是:
在函数 'int main()' 中: 6:25: 错误: 获取临时地址 数组
我知道这个论点是暂时的,在执行这个foo(...)
语句后会被清理。但是为什么编译器将这种情况视为错误?
现在,如果我在两者之间添加std::move
:
foo(std::move(argType{"a","b"}));
海湾合作委员会停止抱怨。为什么?
代码正确;argType{"a","b"}
是类型const char *[2]
(C++17 [expr.type.conv]/2) 的 prvalue,数组到指针的转换可以应用于数组 prvalue ([conv.array]/1),该数组对 prvalue 执行临时具体化,并且临时持续到完整表达式结束。
所以我认为这是一个 gcc 错误。
相关文章:
- Usages of std::move
- 在C++中对T*类型执行std::move的意外行为
- 关于std::move的使用,是否有编译警告
- 我应该实现右值推送功能吗?我应该使用std::move吗
- 通过实例理解std::move及其目的
- 返回一个带有 std::move 的对象并链接函数
- 当 std::move 与 C 样式数组或不移动对象时会发生什么
- std::move a const std::vector in a lambda capture
- "std::forward"和"std::move"真的不生成代码吗?
- 如何在没有 std::move 的情况下移动临时对象
- 关于在成员重载中使用 std::move() 的问题
- 显式清除 std::move 之后的源资源
- std::move 如何使原始变量的值无效?
- 复制elision、std::move和链式函数调用
- 如果真的需要std::move,我们应该什么时候声明右值refs
- 使用std::move将std::unique_ptr作为qt信号参数传递
- 无法使用带有 std::move 的自定义删除器插入 std::unique_ptr
- C++:我应该在 return 语句中显式使用 std::move() 来强制移动吗?
- 编译器是否足够聪明,以至于 std::move 变量超出范围?
- std::move() 或其在局部变量上的显式等价物可以允许 elision 吗?