Why can't we define re-assignable const reference variable?

Janice Caron caron800 at googlemail.com
Sat Feb 16 23:34:14 PST 2008


On 16/02/2008, none <z at gg.com> wrote:
> What I mean is in C++, you can define 2 different kinds of C++ pointers:
> Sorry in C++, it should be
>
> (1) C* const b;  // b can be re-bind, but the object cannot be modified
>
> (2) const C* b and const C* const b;  // both pointer, and data are const.

I think you mistyped. (1) means "b is a const pointer to mutable
data". In this case, therefore, b cannot be rebound. That would not be
allowed in D because it breaks transitivity. On the other hand, the
sentiment you expressed: "b can rebind, but the object cannot be
modifed", can be expressed in both C++ and D as

    C const * b // C++
    const C * b // C++, alternative syntax
    const(C)* b // D

"Both pointer and data are const" can be written in both languages as

    C const * const b // C++
    const C * const b // C++, alternative syntax
    const C* b; // D
    const(C*) b; // D, alternative syntax

Both of my D examples assumed that the object C has been declared as a
struct (in D), because otherwise you can't make an equivalence with
C++. If C had been declared as a class in D, then things look a little
different

    auto b = new C; // D

There is no exact equivalent built into C++, although you can
construct one artificially.

    C& b = *(new C()); // C++

This b will now behave just like a D reference. the C instance is on
the heap, as required, and b is on the stack and four bytes big, as
required. Now let's see what kind of constancy you can get:

    (1) C& b = ...
    (2) C& const b = ...
    (3) C const & b = ...
    (4) C const & const b =

What may not be immediately obvious is that (1) and (2) are completely
identical, because references in C++ are /always/ const. Likewise, (3)
and (4) are completely identical, for the same reason.

You absolutely /cannot/ do "mutable reference to const data" in C++.
It's impossible. The best you can do is "mutable pointer to const
data", and you /can/ do that in D. We're not missing out here!



More information about the Digitalmars-d mailing list