[patch] const_cast to be replaced by str_unconst

Hi all,

I'd like to introduce a new function:

    char *str_unconst(const char *);

The function returns a string that compares equal to its argument, but does not have the "const" qualifier. Currently it just returns its argument, cast to (char *).

I like this version much more than the const_cast macro I introduced some months ago. Compare these:

    ms = const_cast(char *, cs);
    ms = str_unconst(cs);

The latter is shorter, has fewer chances for typing errors and is not as powerful as the former. You could have passed an int (or any other value) before, and that had been converted (or promoted, or whatever that type cast means in that case) to a char *. That took an important possibility to check for bugs from the compiler.

There's also the naming issue. Apparently, Bjarne Stroustrup has not had enough letters to name the const_cast unconst_cast, which would be more appropriate. The current name is just misleading, so I want to abandon it.

For those of you that are concerned about the performance loss of an extra function call: It is much more important for the code to be readable and checkable by the compiler than to be 1 millisecond faster at all.

Index: src/util.h
RCS file: /cvsroot/mc/mc/src/util.h,v
retrieving revision 1.66
diff -u -p -r1.66 util.h
--- src/util.h	8 Feb 2005 10:46:01 -0000	1.66
+++ src/util.h	12 Apr 2005 10:33:49 -0000
@@ -3,6 +3,12 @@
 #include <sys/types.h>
+/* Returns its argument as a "modifiable" string. This function is
+ * intended to pass strings to legacy libraries that don't know yet
+ * about the "const" modifier. The return value of this function
+ * MUST NOT be modified. */
+extern char *str_unconst (const char *);
 /* String managing functions */
 extern const char *cstrcasestr (const char *haystack, const char *needle);
Index: src/util.c
RCS file: /cvsroot/mc/mc/src/util.c,v
retrieving revision 1.125
diff -u -p -r1.125 util.c
--- src/util.c	23 Mar 2005 05:29:06 -0000	1.125
+++ src/util.c	12 Apr 2005 10:33:47 -0000
@@ -1441,3 +1441,9 @@ cstrcasestr (const char *haystack, const
     return NULL;
+extern char *
+str_unconst (const char *s)
+	return (char *) s;

[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]