从 C++17 开始(更准确地说,从 p0135r1 开始),数组到指针的转换涉及临时物化 - conv.array :
An lvalue or rvalue of type “array of N T” or “array of unknown bound of T” can be converted to a prvalue of type “pointer to T”. The temporary materialization conversion ([conv.rval]) is applied. The result is a pointer to the first element of the array.
为什么?临时物化仅适用于纯右值 - conv.rval :
A prvalue of type T can be converted to an xvalue of type T. This conversion initializes a temporary object ([class.temporary]) of type T from the prvalue by evaluating the prvalue with the temporary object as its result object, and produces an xvalue denoting the temporary object. T shall be a complete type.
那么,在数组到指针转换的情况下,临时物化应用于什么?指向生成的指针纯右值?
在下面的例子中是否发生了临时物化?
void foo(int *a) {}
int main() {
int arr[4];
foo(arr);
}
最佳答案
临时物化转换应用于要转换的数组(如果它是纯右值)。这是因为指针只能指向实际存在的东西。它不适用于生成的指针值。在您的示例中,要转换的数组是左值,因此不应用转换。
在下面的代码中,数组 prvalue Arr{0, 1}
被转换为 int*
。应用临时物化转换。
void f(int*) {}
int main()
{
using Arr = int [2];
f(Arr{0, 1});
}
GCC好像不接受这段代码,但是按照标准这段代码是没有问题的。参见 Why does passing a temporary object as an argument need std::move?
关于c++ - 数组到指针转换期间的临时物化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57392150/