请举例说明Lvalue-to-rvalue转换去除cv限定符的场景
符合C++23左值到右值转换规则的示例
规则回顾
根据C++23标准中关于左值到右值转换([conv.lval]#1)的规定:
非函数、非数组类型T的glvalue可转换为prvalue。44
若T为不完全类型,则需要进行此转换的程序为病态。
若T为非类类型,则prvalue的类型为T的cv无修饰版本。
否则,prvalue的类型为T。45
示例代码
下面是满足要求的具体代码:
#include <type_traits> int main() { // 1. T为const限定的非类类型 const int const_left_val = 42; auto pr_val1 = const_left_val; // 验证转换后类型为std::remove_cvref_t<const int>(即int) static_assert(std::is_same_v<decltype(pr_val1), std::remove_cvref_t<const int>>); // 2. T为volatile限定的非类类型 volatile int volatile_left_val = 100; auto pr_val2 = volatile_left_val; static_assert(std::is_same_v<decltype(pr_val2), std::remove_cvref_t<volatile int>>); // 3. T为const volatile限定的非类类型 const volatile int cv_left_val = 200; auto pr_val3 = cv_left_val; static_assert(std::is_same_v<decltype(pr_val3), std::remove_cvref_t<const volatile int>>); // 4. T为引用类型的非类glvalue int raw_val = 50; int& ref_left_val = raw_val; auto pr_val4 = ref_left_val; // std::remove_cvref_t<int&>的结果为int,与转换后prvalue类型一致 static_assert(std::is_same_v<decltype(pr_val4), std::remove_cvref_t<int&>>); }
示例说明
- 所有初始变量均为非类类型T的glvalue:比如
const int const_left_val是const int类型的左值(glvalue的一种);int& ref_left_val是绑定到int对象的左值,其底层对象类型为非类类型。 - 赋值操作触发左值到右值转换:编译器在将左值赋值给新变量时,会自动执行该转换以生成右值。
- 转换后得到的prvalue类型恰好是
std::remove_cvref_t<T>:对于带cv限定的非类类型,转换会去掉const/volatile限定;对于引用类型,std::remove_cvref_t会剥离引用属性,最终结果与转换后的prvalue类型完全匹配。
内容的提问来源于stack exchange,提问作者Dr. Gut
相关产品推荐
相关产品推荐

