A const use-case I would NOT like to see replicated

Tim Keating holyspamster at gmail.com
Thu Jun 21 16:43:37 PDT 2007


I have been following the discussion on const/invariant/final, and while 
I understand the need to add this feature to the language, my initial 
reaction was repugnance. In order to add value and not just fan a 
flame-war, I spent some time ruminating on why this is so. As a result, 
I recalled a use case for const in C++ that caused me considerable pain, 
and so I throw it out here for discussion.

My main issue is with const-correct programs passing data to 
non-const-correct libraries. For example, consider extracting string 
data from a std::string to pass to a library written in C (using the 
c_str() member func). If the function you want to call takes a const 
char*, as it should, then great, you're fine. If it takes only a char* 
(which I have seen happen plenty of times), you're screwed. Your choices 
are:

1) Fix the function. Even if you *can* do this (i.e the library is not 
open-source, or in a legacy library that you're forbidden to modify, or 
part of the fastest linker in the world that no one understands anymore 
and you don't dare update), it could well be that making the function 
argument const will break too much dependent code to make it 
realistically feasible.
2) Cast away the constness, perhaps in a wrapper function. Yuck, 
basically. Casting away constness should only rarely be necessary, if 
ever. This is too common a use case for that to be the standard behavior.
3) Dupe the function and make a const flavor of it. This isn't 
*terribly* egregious if the function doesn't change very often, but if 
it has to be maintained you're asking to get bitten by a subtle bug.

Either there should be a simple, idiomatic solution to this problem, or 
(if possible) the compiler should determine whether the const reference 
is modified by the called function. If not, it should allow you to pass 
the const reference. In other words: although the const type attribute 
is a guarantee that a function WILL NOT modify your data, its absence 
should not automatically imply that the function WILL modify your data.

I'm not a compiler writer. I don't know whether doing that is hard, or 
even feasible. But there's my $0.02.

TK



More information about the Digitalmars-d mailing list