为什么const对象的成员变量不是const

Why member variables of a const object are not const

本文关键字:const 变量 对象 为什么 成员      更新时间:2023-10-16

刚刚问了一个类似的问题,归结起来就是这个。

#include <iostream>
using namespace std;
struct A {
    A() : a{1} {};
    int a;
};
template <typename Which>
struct WhichType;
int main() {
    const A a;
    const A& a_ref = a;
    const A* a_ptr = &a;
    WhichType<decltype(a.a)> which_obj; // template evaluates to int
    WhichType<decltype(a_ref.a)> which_ref; // template evaluates to int
    WhichType<decltype(a_ptr->a)> which_ptr; // template evaluates to int
    return 0;
}

为什么模板不变成const int而变成int ?

decltype给出了操作数的"声明类型",当它没有被额外的括号括起来时。

要获得表达式的实际类型,即const int,您必须编写decltype((a.a)),以此类推。

decltype总是返回左值表达式的引用类型,而不是名称。

当传递标识符(或成员)的名称时,它返回声明的类型。

当传递一个不同的表达式时,它返回更接近你想要的结果,但是引用限定。

WhichType<std::remove_reference_t<decltype((a_ptr->a))>> which_ptr; // template evaluates to const int!

生活的例子或者如果您想要l/r值:

WhichType<decltype((a_ptr->a))> which_ptr2; // template evaluates to const int&
WhichType<decltype(((const A){}.a))> which_ptr3; // template evaluates to const int

你可以在这里添加&&,使它成为一个"真正的"右值引用。

WhichType<decltype(((A){}.a))&&> which_ptr4; // template evaluates to int&&!

生活例子。