Jump to content

Top level const vs Low level const

Go to solution Solved by zahlio,

 

A top level const qualifier affects the object itself. Others are only relevant with pointers and references. They do not make the object const, and only prevent modification through a path using the pointer or reference. Thus:

char x;char const* p = &x;

This is not a top level const, and none of the objects are immutable. The expression *p cannot be used to modify x, but other expressions can be; x is not const. For that matter *const_cast<char*>( p ) = 'x' is legal and well defined.

But

char const x = 'x';char const* p = &x;

This time, there is a top level const on x, so x is immutable. No expression is allowed to change it (even if const_cast is used). The compiler may put x in read only memory, and it may assume that the value of x never changes, regardless of what other code may do.

To give the pointer top level const, you'd write:

char x = 'x';char *const p = &x;

In this case, p will point to x forever; any attempt to change this is undefined behavior (and the compiler may put p in read-only memory, or assume that *p refers to x, regardless of any other code).

Stolen from: http://stackoverflow.com/questions/7914444/what-are-top-level-const-qualifiers

 

A top level const qualifier affects the object itself. Others are only relevant with pointers and references. They do not make the object const, and only prevent modification through a path using the pointer or reference. Thus:

char x;char const* p = &x;

This is not a top level const, and none of the objects are immutable. The expression *p cannot be used to modify x, but other expressions can be; x is not const. For that matter *const_cast<char*>( p ) = 'x' is legal and well defined.

But

char const x = 'x';char const* p = &x;

This time, there is a top level const on x, so x is immutable. No expression is allowed to change it (even if const_cast is used). The compiler may put x in read only memory, and it may assume that the value of x never changes, regardless of what other code may do.

To give the pointer top level const, you'd write:

char x = 'x';char *const p = &x;

In this case, p will point to x forever; any attempt to change this is undefined behavior (and the compiler may put p in read-only memory, or assume that *p refers to x, regardless of any other code).

Stolen from: http://stackoverflow.com/questions/7914444/what-are-top-level-const-qualifiers

Best regards Zahlio,
Unity asset developer - Game developer (http://playsurvive.com) - Computer Science student

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×