logical const is a subset of transitive const
Janice Caron
caron800 at googlemail.com
Fri Sep 14 23:57:55 PDT 2007
On 9/15/07, Janice Caron <caron800 at googlemail.com> wrote:
> The irony is that a C++ const std.string is only /logically/ const,
> not physically const, because it has a mutable reference counter in
> it.
(I don't think it actually uses the mutable keyword in its source
though. mutable members and intransitive const are to some extent
interchangeable).
So here's how it works. A C++ std.string is a reference object, like a
class in D. The class data (on the heap) contains a reference counter.
When you copy a string, you get one more pointer to the same
heap-data, but the reference counter is incremented. When you destroy
a string, the reference counter is decremented, and the heap data is
not freed unless the reference counter reaches zero.
So, consider the following C++ code:
const string s1 = "hello";
const string s2 = s1;
That's like, in D:
class String { /* whatever */ }
const String s1 = new String("hello");
const String s2 = s1.dup();
...where s1.dup() MODIFIES s1 (increments a reference counter) despite
s1 being const.
It is allowed to do this because const is not transitive in C++
More information about the Digitalmars-d
mailing list