On Fri, 2025-03-14 at 17:13 +0100, Bonita Montero wrote:
Am 14.03.2025 um 16:56 schrieb wij:
If it tries to exceed 'High level assembly', it could be ridiculous.
Same as C++, if it tries to be 'not-C'.
Thiago wants to mimic construction with new,
I've been wondering how C would mimic ctor/dtor for long long time,...
void * init_malloc(size_t size, void * src) looked reasonable, and
may be necessary in 'my assembly model'.
What is your opinion about init_malloc?
One problem it solves it to initialise a const objects on heap.
What is your opinion about init_malloc?
One problem it solves it to initialise a const objects on heap.
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
void * init_malloc(size_t size, void * src)
{
void * p = malloc(size);
if (p) {
memcpy(p, src, size );
}
return p;
}
#define ALLOC(OBJ) ((typeof(OBJ)*) init_malloc(sizeof(OBJ), &(OBJ)))
////////// SAMPLE //////////
struct Mail {
const int id;
};
int main () {
struct Mail* p0 = ALLOC((struct Mail){.id= 1});
struct Mail* p1 = init_malloc(sizeof *p1, &(struct Mail){.id= 1});
auto p2 = ALLOC((struct Mail){.id= 1});
}
On 2025-03-14, Thiago Adams <thiago.adams@gmail.com> wrote:
What is your opinion about init_malloc?
One problem it solves it to initialise a const objects on heap.
I don't think it's that useful, because I would rather write a
type-specific allocating constructor:
struct Mail *Mail_alloc(int id) { /* ... you know what goes here ... */ }
No games with macros and struct literals that we hope the
compiler optimizes away.
Sysop: | Keyop |
---|---|
Location: | Huddersfield, West Yorkshire, UK |
Users: | 546 |
Nodes: | 16 (1 / 15) |
Uptime: | 159:29:45 |
Calls: | 10,385 |
Calls today: | 2 |
Files: | 14,056 |
Messages: | 6,416,491 |