Indirect call of non-const function on const object

Given the following code:

class foo;

foo* instance = NULL;

class foo
{
public:
   explicit foo(int j)
    : i(j)
   {
      instance = this;
   }

   void inc()
   {
      ++i;
   }

private:
   int i;
};

Is the following use of certain behavior?

const foo f(0);

int main()
{
   instance->inc();
}

I ask because I use the class registry, and since I am not modifying directly f, it would be nice to do it const, but then the fregistry is indirectly modified.

EDIT: I mean specific behavior: Is the object placed in any special memory location that can only be written once? Read-only memory is out of the question, at least until constexpr from C ++ 1x. For example, constant primitive types (often) are placed in read-only memory, and execution const_castcan lead to undefined behavior, for example:

int main()
{
    const int i = 42;
    const_cast<int&>(i) = 0; // UB
}
+3
7

, undefined 7.1.5.1/4:

, , mutable (7.1.1), , const (3.8) undefined.

, , (3.8/1).

+3

const , , undefined.

, , : , const () , "" -const , .

, ctor, . , ctor / - ( ) . ( ) const . , , , "" , (, , ) . /, .

+2

, mutable:

mutable int i;

i , const. , , .


:

class SomeClass
{
// ....
    void DoSomething() { mMutex.lock(); ...; }
    mutable Mutex mMutex;
}

DoSomething() , mMutex , . mutable, SomeClass const ( muetx ).

+1

- non-const ( ) const . , : const_cast, , .

, -, , (.. ). undefined. inc , , undefined.

.

+1

const cast?

const, ?

:

explicit foo(int j = 0)    : i(j)   

{    instance = this;   }
0

. i , , mutable int i;. const - , i . , i - , .

, , , , , . foo* instance = NULL; ( ), NULL instance, const; f, const, .

0

In GCC, at least your constructor should be explicit foo(int j)with a word int.

However, it's nice to have two pointers to the same value, one constand not the other.

0
source

Source: https://habr.com/ru/post/1726151/


All Articles