Physical consistency class

I am learning the "C ++ Programming Language" from Bjarne Stroustrup, and it talks about the logical and physical constant of the class.

An example of a logical constant is something like:

class A {
    int m;
    void func() const { m++; } //forbidden
}

You can get around this with a throw, for example:

class A {
    int m;
    void func() const { (A*) this)->m++; } //allowed
}

According to him, the logical constant

"which remains constant for its users.

and physical constant

"stored in read only memory"

As a note, he says that

a physical constant can be forced by placing an object in read only memory for classes without constructors

I did not quite understand this statement. Can someone give an explanation on how to apply a physical constant and why it does not work if the class has a constructor?

+5
5

, , ( ) .

++ ( , ), , , ++

  • /
  • (, , )

/ - , , , . , , : (RO). , , . ++ . ++ . ++, .

. , const. ++.

const double d = 5;
const int i = 42;
const std::string str = "Hello World!";
const MyClass c;

, , RO . , Undefined Behavior (UB), , RO . , , UB ( RO). , , , , . - , , , "" - , - , . UB - UB. .

, , 1- .

, . ++ - . - , .

const MyClass* pc;

const MyClass. , : , , , . "" .

const MyClass c;
pc = &c;

MyClass nc;
pc = &nc;

, p, accss MyClass. () , . , , , . , - , , .

MyClass* p = const_cast<MyClass*>(pc);

(, , ). , Undefined , .

, . A const, , this , , const A*, A, , . , , , const A a;, , , , , RO .

, , follwing

const MyClass* const* const* const p = /* whatever */;

4 const . . . const constness p ( ), const , ( ).

, , "" 2- 3- , 1-, C++ 1- 2-. , , "", , 2- .

+13

, , .

const , , , .

readonly -, ++, , , readonly, .

MSVC ,

#pragma section("rosec",read)
__declspec(allocate("rosec")) int j = 0; // this will be in a readonly data segment.
+5

.

Linux mprotect . Windows API.

, .

, , .

POD, const, .

+3

. , , .

struct A
{
    int x;
    float y;
};

A const a = {5,6.5}; // This object can be built at compile time and placed in read only memory.
+2

, , , / CD-R. . Overkill, , .

, ( ) ( , / JVM). , / ( ).

Thus, so far one assumption mentions marking memory pages manually through your operating system. This is probably your only viable option for industrial strength. This or my equipment offer. Your compiler will not do this for you.

0
source

All Articles