If changing a const object is undefined behavior then how do constructors and destructors operate with write access?

前端 未结 5 1587
名媛妹妹
名媛妹妹 2020-12-11 03:48

C++ standard says that modifying an object originally declared const is undefined behavior. But then how do constructors and destructors operate?



        
5条回答
  •  青春惊慌失措
    2020-12-11 04:11

    Constness for a user-defined type is different than constness for a built-in type. Constness when used with user-defined types is said to be "logical constness." The compiler enforces that only member functions declared "const" can be called on a const object (or pointer, or reference). The compiler cannot allocate the object in some read-only memory area, because non-const member functions must be able to modify the object's state (and even const member functions must be able to when a member variable is declared mutable).

    For built-in types, I believe the compiler is allowed to allocate the object in read-only memory (if the platform supports such a thing). Thus casting away the const and modifying the variable could result in a run-time memory protection fault.

提交回复
热议问题