简体   繁体   中英

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

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.

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).

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.

This looks like the definition of POD in C++03. POD means plain old data. A const global instance of that could be placed in ROM by some compiler and platform.

C++11 adds new language features that can mapped to ROM able. constexpr constructors and standard layout types, between them, may be a reasonable set of restrictions on what some compiler can put into ROM . But this will depend on the compiler's support for ROM ing data.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM