Topic: char * to const char*&


Author: ark@alice.att.com (Andrew Koenig)
Date: 10 Dec 92 13:26:41 GMT
Raw View
In article <JPOLITO.92Dec9155725@sysgem1.encore.com> jpolito@sysgem1.encore.com (Jonathan Polito) writes:

> I am curious to what the current wisdom is on accepting char* as a
> valid argument to a function expecting const char*&

It's invalid, though the reason may not be obvious at first glance.

The main thing to realize is that const char*& means "reference to
pointer to const char" and not "reference to constant pointer to
char" as one might think at first.

That means that in order to accept a char* as an argument, it would
be necessary to convert the char* to a temporary of type const char*
and then bind a reference to that temporary.  However, the reference
does not refer to a const object (because a pointer to const is not
itself a const), so it must be bound to a variable of the same type and
not a temporary.

The thing that makes this example tricky is that if we define

 typedef char* T;

then const T and const char* represent different types! -- const T is
"constant pointer to char" and const char* is "pointer to constant char".

The way to write "constant pointer to char" without a typedef it
char *const&, so the following should be OK:

 extern void f(char *const&);

 main()
 {
  char* p = /* some value */;
  f(p);
  // ...
 }

Here, p is of type "pointer to char" and there is no problem binding to
p a "reference to constant pointer to char".
--
    --Andrew Koenig
      ark@europa.att.com




Author: jpolito@sysgem1.encore.com (Jonathan Polito)
Date: Wed, 9 Dec 1992 20:57:25 GMT
Raw View
I am curious to what the current wisdom is on accepting char* as a
valid argument to a function expecting const char*& e.g.
class foo {
public:
 void bar(const char*& n);
}
void sna(foo * FooPtr)
{
 char * n;
 FooPtr->bar(n);
}


The ARM doesn't explicitly allow this nor does it apparently disallow
this. Allowing this conversion does cause unsafe behaviour since then
one could do something like:
void f(const char *&p1, const char **p2)
{
 p1 = *p2;
}

int main (void)
{

 const char * p = "const string";
 const char ** cp1 = &p;
 char * ptr;

 f(ptr,cp1);
 *ptr = 'X'; // const string modified!
}

though this is a evil example.

Thanks in advance,

Jonathan.
--
Jonathan E. Polito (jpolito@encore.com)                 +1 919 481 3730
Encore Computer Corp, 901 Kildaire Farm Rd, bldg D, Cary, NC 27511  USA