简体   繁体   中英

violation of const variable using a pointer c++

Why i am allowed to change a const value without errors?

void foo(long * a)
{
    *a = 50;
}

int _tmain(int argc, _TCHAR* argv[])
{
    const long a = 7; 
    const long * b = &a;

    foo((long *)b);
    // now the value of a is 50
}

You're not .

When you wrote that C-style cast, you disabled the checks. If you'd written this:

foo(static_cast<long*>(b));

or just

foo(b);

then your program would not have compiled.

In order to allow you to do expert magic, you can still write:

foo(const_cast<long*>(b));

but then it's still your responsibility to ensure that you do not use it for evil, such as the evil in your example.

Because you casted the constness away with the cast (long*) . Your program engenders undefined behavior as you attempt to modify a const object.

Especially when casting pointers you should rely on the C++-Casts ( static_cast , reinterpret_cast ), which do not implicitly cast away constness as the C-style cast does. That can only be done explicitly using const_cast , which is almost exclusively used for APIs with lacking const-correctness (and some hacks).
If you try to pass the argument without the cast (which is the way that arguments should usually be passed to functions):

foo(b);

You will get an appropriate error message .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM