C ++,const_cast怀疑。如果我指向const变量并更改其值,为什么它保持不变? [英] C++, const_cast doubt. If I point to const variable and change its value, why it remains the same?

查看:181
本文介绍了C ++,const_cast怀疑。如果我指向const变量并更改其值,为什么它保持不变?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果你有一个变量指向另一个变量,是不是应该更改它的值正弦更换值?

If you have a variable pointing at another, isn''t supposed to change its value sine its replacing the value?

#include <iostream>

using namespace std;

void print (char * str)
{
    *str = 'd';
  cout << *str << endl;
}

int main(void)
{
    const char c = 's';

    print(const_cast<char*>(&c));
    cout << c << endl;
    cin.get();

    return 0;
}





输出:



d

s



Output:

d
s

推荐答案

含义 const 已更改:



在C ++ 98中: const 意味着逻辑上是const,但是从C ++ 11开始 const 现在是线程安全的 - 意味着它必须是按位const。所以编译器可以自由重写:

The meaning const has been changed:

In C++98: const meant logically const, but as of C++11 const is now thread safe - meaning that it has to be bitwise const. So the compiler is free to rewrite:
cout << c << endl;



as:


as:

cout << ''s'' << endl;





按位常量意味着对象或变量中的每一位都是永久性的。



最好的问候

Espen Harlinn



Bitwise const means that every bit in the object or variable is permanent.

Best regards
Espen Harlinn


根据文档 [ ^ ]:

According to the documentation[^]:
Depending on the type of the referenced object, a write operation through the resulting pointer, reference, or pointer to data member might produce undefined behavior.



因为 c 是一个 const char 变量编译器可能正在将值保存在CPU寄存器中,而不是期望它更改,因此它永远不会从内存中重新读取它。结果是你看到的行为。



试试这个:


Because c is a const char variable the compiler is probably saving the value in a CPU register, not expecting it to change so it never actual re-reads it from memory. The result is the behaviour you are seeing.

Try this:

#include <iostream>

using namespace std;
 
void print (char * str)
{
    *str = 'd';
  cout << *str << endl;
}
 
int main(void)
{
    const char c = 's';
 
    print(const_cast<char*>(&c));
    cout << c << endl;
    cout << *(const_cast<volatile char *>(&c)) << endl;
    cout << c << endl;

    cin.get();
 
    return 0;
}


这篇关于C ++,const_cast怀疑。如果我指向const变量并更改其值,为什么它保持不变?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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