cppannotations/yo/first/constcast.yo
2009-10-25 16:44:33 +00:00

17 lines
1 KiB
Text

The tt(const) keyword has been given a special place in casting. Normally
anything tt(const) is tt(const) for a good reason. Nonetheless situations
may be encountered where the tt(const) can be ignored. For these special
situations the tt(const_cast) should be used. Its syntax is:
centt(const_cast<type>(expression))
A ti(const_cast<type>(expression)) expression is used to undo the
tt(const) attribute of a (pointer) type.
The need for a tt(const_cast) may occur in combination with functions from
the standard bf(C) library which traditionally weren't always as const-aware
as they should. A function tt(strfun(char *s)) might be available, performing
some operation on its tt(char *s) parameter without actually modifying the
characters pointed to by tt(s). Passing tt(char const hello[] = "hello";) to
tt(strfun) will produce the warning
centt(passing `const char *' as argument 1 of `fun(char *)' discards const)
A tt(const_cast) is the appropriate way to prevent the warning:
centt(strfun(const_cast<char *>(hello));)