Possible Duplicates:
What is Type-safe?
What is type-safety?
I was reading about c++ vectors and it was mentioned that memcpy
and printf
functions from C are not type safe. Article here: http://en.wikipedia.org/wiki/Vector_(C%2B%2B).
Question: In simple English, what is type safety and what are the "type safe" alternatives?
In the context of denotational semantics, type safety means that the value of an expression that is well-typed, say with type τ, is a bona fide member of the set corresponding to τ. This formal type-theoretic definition of type safety is considerably stronger than what is understood by most programmers.
Type safety means that the compiler will validate types while compiling, and throw an error if you try to assign the wrong type to a variable. Some simple examples: // Fails, Trying to put an integer in a string String one = 1; // Also fails.
A language is type-safe if the only operations that can be performed on data in the language are those sanctioned by the type of the data. Java is not type-safe, though it was intended to be. A Java object may read and modify fields (and invoke methods) private to another object.
Type safety in the source code is a programming language control that ensures that any variable access only its authorized memory locations in a well-defined and permissible way. In other words, the type safety feature ensures that the code doesn't perform any invalid operation on the underlying object.
Type safety means that the compiler can check whether you're using the right types. For example, if you're using printf
, you could accidentally crash your program by writing this:
printf("The meaning of life is %s", 42);
because 42 is an integer, not a string.
Type safety means that the compiler will help check that you don't mix (incompatible) data types.
For instance, when you call memcpy
, the function (and compiler) only sees two pointers in memory, and will happily start copying data. This means you can mix incompatible data types like this:
SomeClass a; AnotherClass b; memcpy((void*)&a, (void*)&b, sizeof(b));
There are many approaches to gaining type safety. You could use templates and make a wrapper around mempcy(), ensuring that the two pointers point to the same data type, or you could use other ways.
Since you are already using vectors from the STL, you are already using a more or less type safe implementation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With