开发者

Smart Pointer Implementation in C [duplicate]

This question already has answers here: 开发者_高级运维 Closed 12 years ago.

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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜