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.
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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With