Skip to content

Type safety

wikipedia Type safety

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 behaviour caused by a discrepancy(不相符) between differing data types for the program's constants, variables, and methods (functions), e.g., treating an integer (int) as a floating-point number (float). 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.

Type enforcement can be static, catching potential errors at compile time, or dynamic, associating type information with values at run-time and consulting them as needed to detect imminent(即将到来的) errors, or a combination of both.

The behaviors classified as type errors by a given programming language are usually those that result from attempts to perform operations on values that are not of the appropriate data type. This classification is partly based on opinion; it may imply that any operation not leading to program crashes, security flaws or other obvious failures is legitimate and need not be considered an error, or it may imply that any contravention of the programmer's explicit intent (as communicated via typing annotations) to be erroneous and not "type-safe".

In the context of static (compile-time) type systems, type safety usually involves (among other things) a guarantee that the eventual value of any expression will be a legitimate member of that expression's static type. The precise requirement is more subtle than this — see, for example, subtype and polymorphism for complications.

nNOTE: type of expression;

Type safety is closely linked to memory safety, a restriction on the ability to copy arbitrary bit patterns from one memory location to another.

NOTE:

1、type safe是memory safe的一个充分条件;

2、使用interpretation model来理解上面这一段

Most statically typed languages provide a degree of type safety that is strictly stronger than memory safety, because their type systems enforce the proper use of abstract data types defined by programmers even when this is not strictly necessary for memory safety or for the prevention of any kind of catastrophic failure.

素材

C++ parameter pack VS C variadic parameter

最能够体现type safety的就是"C++ parameter pack VS C variadic parameter",在下面文章中,讨论了这个topic:

1、eli.thegreenplace Variadic templates in C++

这篇文章有着较好的论述。

2、stackoverflow Variable number of arguments in C++? # A

3、cppreference Variadic arguments

4、Comparison-of-programming-language\C++VS-C\Type-system 章节

5、C++ Core Guidelines # P.4: Ideally, a program should be statically type safe