In computer science, type safety is the extent to which a programming language discourages or prevents type errors. A type error is erroneous or undesirable program behavior caused by a discrepancy between differing data types.

类型安全是指某种编程语言是否阻止类型错误。类型错误是指由于不同类型的差异所引起的错误的或不是期望的程序行为,简单来说,类型错误就是由于不同类型的差异(类型的大小、类型的数据布局方式等)所引起的bug。

Type safety is sometimes alternatively considered to be a property of a computer program rather than the language in which that program is written; that is, some languages have type-safe facilities that can be circumvented by programmers who adopt  practices that exhibit poor type safety. The formal type-theoretic definition of type safety is considerably stronger than what is understood by most programmers.

类型安全有时也被认为是程序的属性,而不是语言的属性; 也就是说,有些语言有类型安全的机制,但是程序员可以使用一些poor type safety的方式绕过这些机制。【不太明白,似乎说的不是一回事】

C

The C programming language is typesafe in limited contexts (when dealing in pointers to structs—a compile-time error is generated when an attempt is made to convert a pointer to one type of struct to a pointer to another type of struct).

C语言不是类型安全的语言,但在特定的环境下可以认为是类型安全的。 例如在处理struct指针时,如果试图将某个struct的指针转成另外一个struct的指针时会出现一个编译时错误。

 

C++

C++ is more type-safe than C when used properly[citation needed] (avoiding the use of void pointers and casting between pointers of two types). Features of C++ that promote code that is less at risk of type errors include:

如果使用恰当,C++比C更加类型安全【避免使用void指针、在两个类型的指针之间做Cast】。C++可以减少类型错误的Feature包括如下几点:

The new operator returns a pointer of a specific type based on the operand, versus the void pointer from C's malloc.

new操作符会根据操作数返回一个特定类型的指针,不像C语言中的malloc会返回void类型的指针;
Certain code written in C that uses void pointers can be rewritten using C++ templates to give a type to an argument whose type is variable.

用C语言中的void指针写出的某些code可以使用C++模板重写;
See static_cast and dynamic_cast.

static_cast 和 dynamic_cast 可以帮助减少类型错误;

 

C#
C# is type-safe. It has support for untyped pointers, but this must be accessed using the "unsafe" keyword which can be prohibited at the compiler level. It has inherent support for run-time cast validation. Casts can be validated by using the "as" keyword that will return a null reference if the cast is invalid, or by using a C-style cast that will throw an exception if the cast is invalid.

C#是类型安全的。它也支持无类型指针,但是必须使用unsafe关键字访问,这在编译时就可以被检查到。 它内置就是支持runtime cast validation。 Cast可以使用as 关键字来做验证,如果cast操作是不合法的,那么会返回null。而如果使用C风格的cast会在cast不合法时抛出Exception。