C++ Logo

std-proposals

Advanced search

Re: [std-proposals] std::is_read_only_memory

From: Sebastian Wittmeier <wittmeier_at_[hidden]>
Date: Wed, 1 Apr 2026 14:13:38 +0200
That is either very implementation or operating system dependent (so perhaps no fit for the standard library) or has to be defined in terms of C++.   Perhaps define a template<T>, which signifies that an object of type template<T> is  - containing a T as sub-object  - const and const_casting the const away is UB, mutable attributes are not allowed or cannot be modfiied without UB  - constructed at compile-time, that is even stricter than constinit, never destructed   then the notion of read-only is inside the type system     Another option would be to ask about a memory pool or allocator.     With std::is_read_only_memory you would also have to check each byte of the object. I think there is no guarantee in C++ that an object is either fully in RO space or fully in RW space.       -----Ursprüngliche Nachricht----- Von:Frederick Virchanza Gotham via Std-Proposals <std-proposals_at_[hidden]> Gesendet:Mi 01.04.2026 13:49 Betreff:[std-proposals] std::is_read_only_memory An:std-proposals <std-proposals_at_[hidden]>; CC:Frederick Virchanza Gotham <cauldwell.thomas_at_[hidden]>;  On a microcontroller that has non-volatile Flash from 0x200 to 0x7FFF, and which has volatile SRAM from 0x8000 to 0x10000, the implementation would be simple:  constexpr bool is_read_only_memory( void const *const begin, void const *const end ) noexcept  {     return begin >= 0x200 && end < 0x8000; }  For a desktop PC program, it would be a little more complicated, for instance on Linux I would expect this to return 'true' for pages of memory that contain the ".rodata" section in the ELF file. Of course "is_read_only_memory" should not be used in scenarios where you will be editing page permissions, or where you write to a microcontroller's Flash at runtime.  The purpose of this function would be to optimise initialisation and copying. For instance if we have a class similar to 'std::string', and if we copy it, there's actually no need to allocate memory and copy the buffer contents -- the new string object can simply refer to the original buffer.  Of course for a desktop PC program, there might have to be a setup routine that keeps track of read-only pages every time "dlopen" or "LoadLibrary" is invoked.  So the constructor of a string class might become something like:  string::string(char const *const p) noexcept {     if ( std::is_read_only_memory( p, p + strlen(p) + 1 ) )     {         this->addr = p;     }     else     {         this->addr = new char[ strlen(p) + 1 ];         strcpy( this->addr, p );     } }     -- Std-Proposals mailing list Std-Proposals_at_[hidden] https://lists.isocpp.org/mailman/listinfo.cgi/std-proposals

Received on 2026-04-01 12:14:36