为什么用纯c写一个通用的容器非常难?

本文深入探讨了使用纯C语言编写通用容器的困难,主要体现在语言缺乏封装支持和数据类型参数传递限制上。通过实例分析,提出了避免直接管理内部字段和手动内存管理的策略。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Writing a generic container in pure C is hard, and 

it’s hard for two reasons:

1. The language doesn’t offer any real support for encapsulation or 

information hiding.  That means that the data structures expose 

information about internal representation right there in the interface 

file for everyone to see and manipulate.  The best we can do is 

document that the data structure should be treated as an abstract 

data type, and that the client shouldn ’t directly manage the fields.  

Instead, he should just rely on  the functions provided to manage the 

internals for him.

2. C doesn’t allow data types to be  passed as parameters.  That means 

a generic container needs to manually manage memory in terms of 

the client element size, not client  data type.  This translates to a 

bunch of malloc, realloc, fr ee, memcpy, and memmove calls 

involving void *s.  This is the  very type of programming that makes 

C difficult.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值