在书中Coders at Work (p355),Guy Steele 谈到 C++:
I think the decision to be backwards-compatible with C is a fatal flaw. It’s just a set of difficulties that can’t be overcome. C fundamentally has a corrupt type system. It’s good enough to help you avoid some difficulties but it’s not airtight and you can’t count on it
他将类型系统描述为“腐败”是什么意思?
你能用一个简单的 C 例子来演示吗?
编辑:
这句话听起来颇有争议,但我并不想这么做。我只是想明白他的意思。
请用 C 而不是 C++ 给出示例。我也对“基本”部分感兴趣:)
最佳答案
C 中非类型安全的明显示例来自于您可以从 void * 转换为任何类型而无需显式转换的事实。
struct X
{
int x;
};
struct Y
{
double y;
};
struct X xx;
xx.x = 1;
void * vv = &xx;
struct Y * yy = vv; /* no need to cast explicitly */
printf( "%f", yy->y );
当然 printf 本身并不是完全类型安全的。
C++ 不是完全类型安全的。
struct Base
{
int b;
};
struct Derived : Base
{
int d;
Derived()
{
b = 1;
d = 3;
}
};
Derived derivs[50];
Base * bb = &derivs[0];
std::cout << bb[3].b << std::endl;
将 Derived* 转换为 Base* 没有问题,但是当您尝试将 Base* 用作数组时会遇到问题,因为它会使指针算术完全错误,而所有 b 值都是 1,您可能会很好得到一个 3(因为整数会变成 1-3-1-3 等)
关于c++ - 解释 "C fundamentally has a corrupt type system",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4124810/