Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Indirectly calling non-const function on a 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 using defined behavior?

const foo f(0);

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

I'm asking because I'm using a class registry, and as I don't directly modify f it would be nice to make it const, but then later on f is modified indirectly by the registry.

EDIT: By defined behavior I mean: Is the object placed into some special memory location which can only be written to once? Read-only memory is out of the question, at least until constexpr of C++1x. Constant primitive types for instance, are (often) placed into read-only memory, and doing a const_cast on it may result in undefined behavior, for instance:

int main()
{
    const int i = 42;
    const_cast<int&>(i) = 0; // UB
}
like image 729
dalle Avatar asked Apr 23 '26 14:04

dalle


2 Answers

Yes, it is undefined behavior, as per 7.1.5.1/4:

Except that any class member declared mutable (7.1.1) can be modified, any attempt to modify a const object during its lifetime (3.8) results in undefined behavior.

Note that object's lifetime begins when the constructor call has completed (3.8/1).

like image 125
avakar Avatar answered Apr 25 '26 03:04

avakar


This may be one of the rare cases where the not very known mutable keyword could be used:

mutable int i;

i can now be changed even if the object is const. It's used when logically the object doesn't change, but in reality it does.


For example:

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

In DoSomething() the object doesn't logically change and yet mMutex has to change in order to lock it. So it makes sense to make it mutable, otherwise no instance of SomeClass could be const (assuming you lock the muetx for every operation).

like image 21
Thomas Bonini Avatar answered Apr 25 '26 04:04

Thomas Bonini



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!