C 中的智能指针实现
可能的重复:
C 语言的智能指针/安全内存管理?
我有一个嵌入式应用程序我在动态内存中分配一个对象并将其传递给其他模块。
我想创建一个指向该对象的智能指针。 C++中有很多使用和实现智能指针的例子。
我正在寻找智能指针的仅 C 语言实现。
谢谢。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
是的,我认为这是不可能的(或者至少没有那么有用),因为@KennyTM 所说的。智能指针之所以成为可能,是因为构造函数和析构函数被自动调用。否则你必须自己调用reference()和unreference()。还有用吗?
另外,请参阅之前的非常相关的SO问题:智能指针/安全内存管理C?
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?
您可以构造一个完全封装的“不透明”类型,并按照您在 C++ 中执行的方式执行您想要的操作。
像这样。
smartpointer.h:
smartpointer.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:
smartpointer.c
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.
我倾向于认为智能指针(至少)为你做两件事:
第二个方面可以通过实现一个强大的 API 来近似,该 API 不允许人们直接复制/分配指针。
但第一项是 C++ 及其对构造函数/析构函数(RAII 的核心)的语言支持真正发挥作用的地方。事实上,构造函数 &析构函数通过编译器自动插入的代码在正确的位置被调用,这使得魔法发挥作用。没有对 CTOR 和 CTOR 的内置语言支持。 DTOR,您只需近似效果,或依赖用户在必要时“做正确的事情”。
I tend to think of smart pointers as doing (at least) 2 things for you:
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.