gpt4 book ai didi

c++ - prvalues的cv-qualifications (revisited)

转载 作者:行者123 更新时间:2023-12-04 04:26:28 29 4
gpt4 key购买 nike

这是我的 previous question 的后续,其中明显的共识是对纯右值的 cv 限定的处理变化只是一个相当小的和无关紧要的变化,旨在解决一些不一致的问题(例如,函数返回纯右值并用 cv 限定的返回类型声明)。
但是,我在标准中看到另一个地方似乎依赖于具有 cv 限定类型的纯右值:const 的初始化通过临时实现转换使用纯右值引用。相关措辞可在 9.3.3/5 中的多个位置找到

[...] If the converted initializer is a prvalue, its type T4 is adjusted to type “cv1 T4” ([conv.qual]) and the temporary materialization conversion ([conv.rval]) is applied [...]

[...] Otherwise, the initializer expression is implicitly converted to a prvalue of type “cv1 T1”. The temporary materialization conversion is applied and the reference is bound to the result.


目的显然是为了确保当我们到达实际的 temporary materialization conversion

7.3.4 Temporary materialization conversion
1 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它作为输入接收的包括所需的 cv 资格。
但是该 cv 资格如何在 7.2.2/2 中存活下来?如果是非类非数组纯右值?

7.2.2 Type
2 If a prvalue initially has the type “cv T”, where T is a cv-unqualified non-class, non-array type, the type of the expression is adjusted to T prior to any further analysis.


或者是吗?
例如。在这个例子中我们得到什么样的临时
const int &r = 42;
是临时的 const或不?我们能做到吗
const_cast<int &>(r) = 101; // Undefined or not?
不触发未定义的行为?如果我没记错的话,最初的意图是获取 const int在这种情况下是临时的。还是真的吗? (对于类类型,答案很明确 - 我们得到一个 const 临时的。)

最佳答案

你为什么怀疑7.2.2的语言? cv 限定符在非类、非数组纯右值上被丢弃似乎非常明确,因此临时实现中的类型 T 是非常量、非 volatile 类型。
如果不是这种情况,那么您将无法将纯右值绑定(bind)到非 const 右值引用。然而,该标准似乎极有可能旨在接受以下程序:

#include <type_traits>

template<typename T> void
f(T &&t)
{
static_assert(std::is_same_v<decltype(t), int&&>);
++t;
}

int
main()
{
f(5);
}

关于c++ - prvalues的cv-qualifications (revisited),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54381791/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com