Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a heap-allocated object be const in C++?

Tags:

In C++ a stack-allocated object can be declared const:

const Class object;

after that trying to call a non-const method on such object is undefined behaviour:

const_cast<Class*>( &object )->NonConstMethod(); //UB

Can a heap-allocated object be const with the same consequences? I mean is it possible that the following:

const Class* object = new Class();
const_cast<Class*>( object )->NonConstMethod(); // can this be UB?

is also undefined behaviour?

like image 387
sharptooth Avatar asked Dec 18 '09 10:12

sharptooth


2 Answers

Yes. It's legal to construct and destroy a const heap object. As with other const objects, the results of manipulating it as a non-const object (e.g. through a const_cast of a pointer or reference) causes undefined behaviour.

struct C
{
        C();
        ~C();
};

int main()
{
        const C* const p = new const C;

        C* const q = const_cast<C*>(p); // OK, but writes through q cause UB

        // ...

        delete p; // valid, it doesn't matter that p and *p are const

        return 0;
}
like image 66
CB Bailey Avatar answered Sep 20 '22 21:09

CB Bailey


In your heap example, new returns a pointer to non-const. The fact that you've stored it in a pointer to const (and then const_casted it back to a pointer to non-const) doesn't change the fact that the object itself is not const in the same way as the stack-allocated one is.

However, you can create a const object on the heap:

const Class* object = new const Class();

In such a case, casting to a pointer to non-const and calling a non-const method would be the same situation as the const stack-allocated object.

(The idea of creating a const object on the heap was new to me, I had never seen that before. Thanks to Charles Bailey.)

like image 11
Greg Hewgill Avatar answered Sep 21 '22 21:09

Greg Hewgill