c++ - const_cast 的行为

标签 c++ casting lvalue rvalue

我正在阅读有关 c++ 中的 const_cast 运算符

1.我无法理解的第一件奇怪的事情是

const_cast 运算符语法即

-const_cast--<--Type-->--(--expression--)--------------------><

我对这种语法的理解是,它有助于摆脱 expression 的常量性。类型 Type .但是考虑这段代码

class  ConstTest {   

private:
    int year;
public:
    ConstTest() : year(2007) {}
    void  printYear() const;
};

int main() {
    ConstTest c;
    c.printYear();
    return  0;
}

void ConstTest::printYear() const {
    ConstTest  *c  = const_cast<ConstTest*>(this);
    c->year  = 42;
    std::cout  <<  "This  is the  year "  << year  << std::endl;
}

这里排队 ConstTest *c = const_cast<ConstTest*>(this) ,我认为 this 的常量指针应该被丢弃,但输出显示它是 this 的对象指失去常量性的。

我感觉代码应该是ConstTest *c = const_cast<ConstTest>(*this) ,但这会产生错误。我知道我在很多解释上都是错误的。请全部改正。

2.我的第二个问题是下面给出的语句

const_cast 表达式的结果是右值,除非 Type 是引用类型。在这种情况下,结果是一个左值。

为什么会这样,为什么在指针的情况下不是这样?

最佳答案

it helps to cast away constness of an expression of type Type

不,Type是结果的类型,而不是操作数的类型。

What i think is const of this pointer should be casted away

this类型为 const ConstTest* . const_cast<ConstTest*>(this)类型为 ConstTest* .这就是从指向 const 的指针“抛弃 const”的意思。

I feel code should have been ConstTest *c = const_cast<ConstTest>(*this)

const_cast<T> 的结果具有类型 T,这就是它的定义方式。也许你会以不同的方式定义它,但运气不好,你没有得到 ConstTest*通过写作 const_cast<ConstTest> , 你可以通过写 const_cast<ConstTest*> 得到它.您的首选语法不可用。

你可以做ConstTest &c = const_cast<ConstTest&>(*this)ConstTest *c = const_cast<ConstTest*>(this) , 所以选择你最喜欢的。

The result of a const_cast expression is an rvalue unless Type is a reference type. In this case, the result is an lvalue.

why so and why it is not true in case of pointers?

指针也是如此。 ConstTest*不是引用类型,const_cast<ConstTest*>(this) 的结果是一个右值。然后将该值赋给变量 c .

关于c++ - const_cast 的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9132315/

相关文章:

c++ - 右值引用被视为左值?

c++ - 析构函数 vs 成员函数竞赛

当类模板 "*"包装在宏中时,C++ 的参数太少

c++ - 我应该如何更改此声明?

c# - 继承类类型转换

c# - 在运行时将 JObject 转换为类型

c - int *x[] 和 int (*x)[] 的区别?

C++/菱形继承(钻石问题)/静态变量

casting - 在 D 中传递带有泛型参数的函数指针

c++ - 赋值运算符的返回类型是什么?