c++ - 数组到指针转换期间的临时物化

标签 c++ language-lawyer

从 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/

相关文章:

c++ - 在 switch 语句中从 int 到 enum 类的隐式转换

c++内存管理局部变量的内存分配

c++ - 涉及继承、指针对象释放以及何时释放的问题

c++ - 类模板偏特化的匹配

所有位 0 都可以是整数的陷阱表示吗?

c++ - 右值到左值的转换?

c++ - DX11 以编程方式填充 3D 纹理

c++ - 通用结束迭代器与容器的可递减要求 `end()`

c++ - 为什么 std::hash 不能保证是确定性的?

c++ - 显式调用模板参数类型的析构函数,即使在内置函数上实例化时也是如此