C++ &引用;“无约束”;通过指针的常量值

C++ &引用;“无约束”;通过指针的常量值,c++,C++,首先,很抱歉可能出现问题冗余 在GCC中使用C/C++指针做一些小实验时,我在绕过指针地址值的恒定性时遇到了这种有点奇怪的行为 #include <iostream> int main() { using namespace std; const double number = 100; //bypassing constantess of pointed-to value double * pointer_to_value = (double *) &am

首先,很抱歉可能出现问题冗余

在GCC中使用C/C++指针做一些小实验时,我在绕过指针地址值的恒定性时遇到了这种有点奇怪的行为

#include <iostream>
int main()
{
    using namespace std;

    const double number = 100;
//bypassing constantess of pointed-to value
    double * pointer_to_value = (double *) &number;
    *pointer_to_value += 200;

    cout << "Adress of number: " << &number << "\tValue of number: " << number << endl <<
    "   Pointer value: " << pointer_to_value << "\tDereferencing pointer: " << *pointer_to_value;

    return 0;
}
#包括
int main()
{
使用名称空间std;
常数双倍数=100;
//绕过指向值的constantess
double*指向值=(double*)和数字的指针;
*指向值+=200的指针;

cout编译器优化。编译器不希望您像那样尝试和欺骗它,它知道值是
const
,所以它只是缓存它。尝试在不进行任何优化的情况下编译它,看看它是否有任何不同

通常,
const
的含义是:

常量-不应修改对象。尝试这样做会导致未定义的行为。在大多数编译器上,这是编译时错误

是的

它发生的确切原因与此无关(实际上是因为编译器将值内联)。

通过指针“UnConsting”const值是一种未定义的行为

因此,无法定义标准未定义的行为。

编译器优化。您可以通过向变量添加
volatile
关键字来克服这一问题

#include <iostream>
int main()
{
    using namespace std;

    volatile const double number = 100;
    //bypassing constantess of pointed-to value
    double * pointer_to_value = (double *) &number;
    *pointer_to_value += 200;

    cout << "Adress of number: " << &number << "\tValue of number: " << number << endl <<
    "   Pointer value: " << pointer_to_value << "\tDereferencing pointer: " << *pointer_to_value;

    return 0;
}
#包括
int main()
{
使用名称空间std;
易失性常数双倍数=100;
//绕过指向值的constantess
double*指向值=(double*)和数字的指针;
*指向值+=200的指针;

cout我的猜测是gcc已经代表您做了一些优化,替换了对
的引用Check out this->“也许编译时优化?@mandy-link应该是(不带引号)您应该使用C++中的STATIC Type和DyrimCype。而不是C编译器操作符。实际上,解决这个问题的可能复制是首先不调用未定义的行为。例如,不尝试修改原来的代码> CONST 。它仍然是未定义的行为。编译器可以放<代码>编号< /代码>。进入只读存储器。非常同意,人们甚至不应该考虑这样做。但这实际上解决了他所期望的问题。