为什么将临时对象作为参数传递需要 std::move?

Why does passing a temporary object as an argument need std::move?

本文关键字:std move 参数传递 临时对象 为什么      更新时间:2023-10-16

我正在尝试通过初始值设定项列表将字符串文本数组传递给仅接受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 错误。