Path: utzoo!utgpu!news-server.csri.toronto.edu!cs.utexas.edu!uunet!cimshop!davidm From: cimshop!davidm@uunet.UU.NET (David S. Masterson) Newsgroups: comp.lang.c++ Subject: Re: const Message-ID: Date: 10 Sep 90 05:55:12 GMT References: <10863@cadillac.CAD.MCC.COM> <142@tdatirv.UUCP> <11306@alice.UUCP> Sender: davidm@cimshop.UUCP Distribution: comp Organization: Consilium Inc., Mountain View, California. Lines: 46 In-reply-to: ark@alice.UUCP's message of 7 Sep 90 15:31:30 GMT In article <11306@alice.UUCP> ark@alice.UUCP (Andrew Koenig) writes: > > If the argument is memory that can't be changed, and the return value > is part of the argument, then the return value had better be immutable > as well. > > I should point out, though, that if you have a pointer to mutable > memory and you convert that pointer to a pointer to const, it is > entirely legitimate to cast it back. Exactly the point of the substring() example. I guess the question here is can the compiler know and keep track of the differences between a pointer to mutable memory and a pointer to immutable memory if both are declared as "const char*"? > Therefore, there's no reason not > to write the following: > > extern const char* substring(const char*, const char*); > inline char* substring(char* p, const char* q) { > return (char*) substring((const char*) p, q); > } > > At first glance, one might think it unnecessary to cast p to > const char*, but one would be wrong: without the cast, the > result would be a recursion loop. Think about it. Obviously, the cast of p is necessary to prevent recursion, but isn't the cast of the return value of substring() a violation of the idea that "once a const, always a const" (which, I thought, was the point of the discussion)? How can the compiler know that the result of: extern const char* substring(const char*, const char*); is mutable because it is a direct result of the p (which is mutable, but casted to const)? It would seem that this could only be known in a separate compilation step. As far as this compilation step is concerned, this substring could work in a couple of ways -- return a pointer into the first argument or copy the first argument to someplace truly read-only and return a pointer to that. The compiler can't know, can it? -- ==================================================================== David Masterson Consilium, Inc. uunet!cimshop!davidm Mtn. View, CA 94043 ==================================================================== "If someone thinks they know what I said, then I didn't say it!"