Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why should a class or struct must have no user defined constructor or destructor to ensure ROMability for const in C++?

Tags:

c++

constants

I was reading a reference on C++ and there I found out that in order to ensure ROMability for an object defined as const :
1.The class or struct must have no user-defined constructors
2.There can be no base classes or member objects with user defined constructors or destructors.
I am taking this in reference to bitwise const and not mutable const.
In my views ,the first one holds because the constructor or destructor modifies the const data members. So, we refrain from using user defined constructor or destructor.
But I can't get a good explaination for the second point.

like image 729
Kavish Dwivedi Avatar asked Nov 30 '25 16:11

Kavish Dwivedi


2 Answers

A constructor / destructs would modify the object, which goes against it being stored in ROM.

If the class contains objects or inherits a constructor, that still is code that must run to construct the object (members are stored together with their parent objects). Which is not possible to do at compile-time (when ROM objects are assembled).

like image 77
Hampus Nilsson Avatar answered Dec 02 '25 05:12

Hampus Nilsson


As you say, the first point is necessary because objects with user-defined constructors are initialised at run-time (during the dynamic initialisation phase before running main, if they have a static lifetime), and so can't be placed in read-only memory since that initialisation must modify the object's memory.

The second point follows from the first - if a (non-static) member or base sub-object has a user-defined constructor, then that constructor must also be used to initialise the member or sub-object at runtime. Therefore, at least part of the object can't be stored in read-only memory; and so the object itself can't be.

like image 27
Mike Seymour Avatar answered Dec 02 '25 05:12

Mike Seymour



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!