views:

146

answers:

3

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.

+2  A: 

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: http://stackoverflow.com/questions/799825/smart-pointers-safe-memory-management-for-c

Scott Stafford
Thanks for the answer. The object is a handle to a Flash Memory. I will use another strategy.
Thomas Matthews
A: 

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.

dmckee
I don't see how this has anything to do with smart pointers...
R..
@R..: Well, this mechanism allows you to support reference counted pointers. It retains the big weakness that you must explicitly delete them before they go out of scope. That's not "smart" in the same way that OO language support, but it does centralize the reference counting code, and make memory management a strictly local affair...as long as you retain the discipline to never break the encapsulation.
dmckee
A: 

I tend to think of smart pointers as doing (at least) 2 things for you:

  • automatically managing lifetime (resource allocation) of the memory/object
  • automatically managing ownership of the object (copy semantics, etc)

The 2nd aspect can be approximated by implementing a strong API that doesn't let people copy / assign the pointers directly.

But the 1st item is where C++ and its language support for constructors/destructors (the heart of RAII) really shine. It's the fact that constructors & destructors get called, by way of code that is inserted automatically by the compiler, at the correct places, which make the magic work. Without built-in language support for CTORs & DTORs, you'll just approximate the effect, or rely on the user to "do the right thing" when necessary.

Dan