原文
| ||||||||||
| ||||||||||
![]() |
原始链接: https://news.ycombinator.com/item?id=43387334
Hacker News上的一篇博客文章讨论了在C语言中实现“愚蠢的智能指针”,引发了热烈讨论。评论者强烈反对这种方法,因为它存在可移植性和安全问题,C语言本身就存在内存不安全的问题。经验丰富的C程序员推荐了替代方案: * 使用`__attribute__((cleanup))`(GCC和Clang可用,有望成为C标准的一部分),例如systemd项目中所用。 * 使用内存池分配器,例如Samba的talloc或Apache的APR。 不推荐使用引用计数,因为它可能导致bug,并且与现代CPU架构不兼容。一位评论者指出,讨论的“智能指针”方法可能会导致分支预测错误,因为这与现代CPU处理返回地址的方式有关。另一位评论者指出,栈保护cookie也可能受到影响。
| ||||||||||
| ||||||||||
![]() |
C programmers are better off with either of these two techniques:
* Use __attribute__((cleanup)). It's available in GCC and Clang, and we hope will be added to the C spec one day. This is widely used by open source software, eg. in systemd.
* Use a pool allocator like Samba's talloc (https://talloc.samba.org/talloc/doc/html/libtalloc__tutorial...) or Apache's APR.
(I didn't include using reference counting, since although that is also widely used, I've seen it cause so many bugs, plus it interacts badly with how modern CPUs work.)
reply