I was wondering whether I could initialize a pointer with constinit in C++20, and I didn't find any adequate answer on the internet. I have a simple code like this:
struct a {
const char *s; // pointer I want to initialize
int other_random_field; // This is another (useless in this case) field
};
constexpr struct a init(void)
{
return {"foo", 4};
}
constinit struct a _ = init();
and compiles perfectly. However I don't see any way to make it work with any different type than char *. What if instead of "foo", I wanted to return an array of ints (whose size is known at compile time) or whatever?
So my real question is: Is there any way to call from my init()
function a malloc()
-like function which gives me the ability to write in a data-segment-allocated buffer?
BTW: The assembly gcc -std=gnu++20
produces is:
.text
.globl _
.section .rodata.str1.1,"aMS",@progbits,1
.LC0:
.string "foo"
.section .data.rel.local,"aw"
.align 16
.type _, @object
.size _, 16
_:
.quad .LC0
.long 4
.zero 4
which is similar to what I want. But instead of putting .string "foo"
I would like to put there, for example, an array of ints.