Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Smart Pointer Implementation in C [duplicate]

Possible Duplicate:
Smart pointers/safe memory management for C?

I have an embedded application where I am allocating an object in dynamic memory and passing it around to other modules.

I would like to create a smart pointer to this object. There are many examples in C++ for using and implementing smart pointers.

I am looking for a C language only implementation of a smart pointer.

Thanks.

like image 522
Thomas Matthews Avatar asked Sep 01 '10 17:09

Thomas Matthews


2 Answers

Yes, I think it's impossible (or at least, not as useful) because of what @KennyTM says. Smart pointers are possible because of constructors and destructors being automatically called. Otherwise you'll have to call reference() and unreference() yourself. Still useful?

Also, see this previous, very related SO question: Smart pointers/safe memory management for C?

like image 99
Scott Stafford Avatar answered Sep 19 '22 16:09

Scott Stafford


You can construct an "opaque" type which is fully encapsulated and do what you want in much the way you would do it in c++.

Like this.

smartpointer.h:

typedef struct sp smartpointer;

smartpointer new(void *content, size_t s);
int          delete(smartpointer p)
void*        dereference(smartpointer p);
/* ... */

smartpointer.c

/* contains the definition of "struct sp" and the implementation of the 
   the functions */

and then promise yourself to never, ever, ever access the data except using dereference, but of course the compiler will not enforce that for you.

So, its all a lot of hassle, and you should think very carefully about what you might gain.

like image 39
dmckee --- ex-moderator kitten Avatar answered Sep 18 '22 16:09

dmckee --- ex-moderator kitten