Bobulate

Home [ade] cookies

Right, Constantly

Markey is right. Some of his commenters are not. So I’ll illustrate, because const-correctness and const-consistency is important for cross-platform quality. In other words, getting it right means that other plaforms than Linux-with-GNU-userland-and-gcc will be able to compile KDE apps in one go.

The main thing about const-consistency is that some compilers mangle the constness of parameters into the function name. Consider the following trivial bit of code:

extern void foo(const int i);

void bar(int i) { };

I compiled this bit on FreeBSD with gcc (which is a platform that doesn’t mangle constness into the name) and Solaris with Sun Studio 12 (which does). The output from nm is like this:

In FreeBSD:
0000000000000000 T _Z3bari
U _Z3fooi

In OpenSolaris:
[22] | 0| 5|FUNC |GLOB |0 |2 |void bar(int)
[__1cDbar6Fi_v_]
[24] | 0| 0|FUNC |GLOB |0 |UNDEF |void foo(const int)
[__1cDfoo6Fki_v_]

The name mangling is clearly different — but note that the parameter of foo() and bar() is typed “i” in both cases by g++, and as “i_v_” and “ki_v_” in Studio. I used nm -C under Solaris to show the de-mangled form of the names as well as the actual symbol. If I add -C against the g++-compiled object, then it prints foo(int) and bar(int) — the constness in the function parameter has disappeared.

The effect of this is that constness does matter on some platforms, and if the interface (e.g. .h file) says “const” then the implementation must do so as well; conversely, if there’s no const in the .h, don’t add a const in the .cc as a safeguard, because it breaks on linking.

As for the stylistic issue of const on POD parameters, well, Ilet’s call that a matter of taste (and the application of the relevant coding style guidelines for the code you’re working on).

Tags: ,