Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

No-copy type annotation

In C, if a structure contains a futex or for whatever reason doesn't make sense to copy or move to a new address, is there any way (type annotation or something) to restrict/warn users from accidentally making copies of those objects?

like image 635
user100046 Avatar asked Jun 19 '26 14:06

user100046


1 Answers

You do could do something similar with opaque type and private encapsulation.

something.h

typedef struct something something; // forward declaration, incomplete/opaque type

something* something_create  (void);
void       something_dostuff (something* obj);

something.c

#include "something.h"

struct something { ... }; // actual definition, only visible privately in this file

something* something_create  (void)
{
  something* result = malloc( sizeof *result );
  ...
  return result;
}

void something_dostuff (something* obj)
{
  /* do stuff on the object */
}

caller.c

#include "something.h"

something* st = something_create();
something_dostuff(st);

Now of course this doesn't stop the caller from doing dirty hacks on purpose such as wild memcpy on the pointed-at data. But is stops a sane application programmer from doing things by mistake, which ought to be the aim of this.

like image 158
Lundin Avatar answered Jun 21 '26 11:06

Lundin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!