开发者

what makes const at the lower levels of the machine?

When making something const in C++ what makes it that you cannot for example implicitly pass it a non-const at the lower levels of the machine? How is it determined by the machine that this is const?

(besides the fact that const means what it means...)

Is it perhaps stored in the .rdata section of memory or is there a bit that gets set that makes it const开发者_如何学Python or how does that work?

Can anyone clarify?


const is mostly a compile-time thing; it doesn't imply anything about where they might be stored at runtime, or whether they might be protected at runtime.

In practice, the compiler may choose to put constants in the program section of the executable, which may be write-protected by the memory-management unit (if it exists). Alternatively, the compiler may fold the constants directly into the code, so that they don't even exist as addressable locations.

Alternatively, it may do none of these things.


const-ness is almost always enforced by the compiler, nothing more, nothing less. No machine protection at all.

Edit: @Oli Charlesworth's answer is better than mine.


"const" does not necessarily mean the storage is read-only. It is a declaration that the C++ program will not change it (and hence that the compiler should reject any attempt to do so). It doesn't mean the value will not change.

It's quite legitimate for a variable to be "const volatile" (the program won't change it, but it might change at any time). A read-only hardware port might well be such a beast, for example.

So at the "lower levels of the machine", nothing needs to be done. The memory is what it is, and the application programmer needs to declare stuff correctly..


In C++, const, rarely has anything to do with hardware. It is mostly a way to tell the compiler that certain kinds of access should result in a compiler error.

The only exception is static const variables of primitive or POD type, which are usually linked into a read-only section in the executable image, and will trigger some kind of page fault if you cast away const-ness and try to modify one of them.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜