C++ Logo

std-proposals

Advanced search

[std-proposals] std::is_read_only_memory

From: Frederick Virchanza Gotham <cauldwell.thomas_at_[hidden]>
Date: Wed, 1 Apr 2026 12:49:07 +0100
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 );
    }
}

Received on 2026-04-01 11:49:09