maedoc / libtvb

TVB C library
6 stars 8 forks source link

Reconsider const on struct members #137

Open maedoc opened 8 years ago

maedoc commented 8 years ago

Initially thought const members were preferable (immutable) but avoided them because in heap-allocated case, it's not as convenient as in C++, but I just remembered that with the C idiom with memcpy, it works just fine:

struct Point { const double x, y; };

struct Point *Point_new(const double x, const double y)
{
    struct Point val = {.x=x, .y=y}, *ptr=malloc(sizeof(struct Point));
    memcpy(ptr, &val, sizeof(struct Point));
    return ptr;
}

It requires a little boilerplate which could be wrapped up in a va macro

#define CONST_INIT(s, p, ...) \
{ \
    struct s _={__VA_ARGS__}; \
    memcpy(p, &_, sizeof(struct s)); \
}

{
  struct Point *p = malloc(sizeof(struct Point));
  CONST_INIT(Point, p, .x=3.4, .y=5.6)
}