const_cast不工作​​c ++? [英] const_cast doesn't work c++?

查看:121
本文介绍了const_cast不工作​​c ++?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

const int k=1;
    int *p=const_cast<int *>( &k);
    cout<<"k before="<<*p<<endl;
    *p=10;
    *const_cast<int *>( &k)=12;
    cout<<"k after="<<k<<endl;

输出为:

k before=1
k after=1

t const cast在这里?

why doesn't const cast work here ?

推荐答案

const_cast 如果您收到一个 const 指向最初未定义为 const 的对象的指针。如果(如你的情况)对象最初定义为 const ,尝试修改它会导致未定义的行为。没有 const_cast ,编译器不会让你甚至尝试这样做(代码不会编译)。

const_cast is normally used when/if you receive a const pointer to an object that wasn't originally defined as const. If (as in your case) the object was originally defined as const, attempting to modify it causes undefined behavior. Without the const_cast, the compiler won't let you even try to do that (the code won't compile).

然而,一个演员告诉编译器你确定你知道你在做什么,它真的很安全,所以编译器只需要关闭并做你所说的,而不是给出任何错误/警告消息它通常可以做。不幸的是,在这种情况下,你所做的是不是真的安全,但因为你告诉编译器关闭并做,你不会得到任何警告(至少与大多数编译器)。

A cast, however, tells the compiler you're sure you know what you're doing and it's really safe, so the compiler just needs to shut up and do what you told it instead of giving any error/warning messages like it might usually do. Unfortunately, in this case what you're doing is not really safe, but since you've told the compiler to shut up and do it, you won't get any warning about it (at least with most compilers).

至于你应该做什么,决定你的 k 或不。如果你真的需要修改它,那么你需要将其定义为一个正常的(非 - const )变量。如果你想确保只有少量的特定代码可以修改它,那么你可以/可以(一种可能性)使其私有一个小类:

As to what you should do, it comes down to deciding whether your k is really const or not. If you really need to modify it, then you need to define it as a normal (non-const) variable. If you want to ensure that only a small amount of specific code can modify it, then you could/can (for one possibility) make it private to a small class:

class my_int { 
    int k;
public:
    my_int() : k(1) {}

    do_mod() { k = 10; }

    operator int() { return k; }
};

现在, do_mod 可以修改 k 。其他代码可以使用 my_int 对象,如同它是一个 int ,但不能修改其值

Now, do_mod can modify k directly. Other code can use a my_int object as if it were an int, but can't modify its value -- in essence, it acts like an rvalue.

为了公平起见,我应该指出,如果它真的试图通过一些转换,其他代码 可以修改 k 的值。正如Bjarne所说,C ++的保护机制旨在防止意外,而不是故意颠覆。

In fairness, I should probably point out that if it really tries by doing some casting, other code can modify the value of k. As Bjarne has said, C++'s protection mechanism is intended to prevent accidents, not intentional subversion.

这篇关于const_cast不工作​​c ++?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆