Problem with const correctness

Jonathan M Davis jmdavisProg at gmx.com
Fri Dec 7 08:59:02 PST 2012


On Friday, December 07, 2012 18:18:30 Gor Gyolchanyan wrote:
> Consider this example:
>  this(this)
> {
> _array = _array.dup;

> Array!int one = Array!int(1, 2, 3, 4, 5);
> immutable Array!int two = one; //Error: conversion error from Array!(int)
> to immutable(Array!(int))
> }
> I enforce value-type semantics by duplicating the arrays on copy, so it
> should behave like a value type with no indirections (implicitly convert to
> immutable).
> What do I need to do for this to work?

Postblit constructors don't work with const or immutable. If I understand 
correctly, Walter and Andrei's solution is to introduce copy constructors, but 
while they've discussed their solution in private, they haven't discussed it 
in detail in the newsgroup.

But when you think about how postblit constructors work, there's really no way 
to make them work with const or immutable. postblit does a bitwise copy of the 
object being copied and then allows you to reassign the member variables other 
stuff (e.g. a deep copy). That reassignment is illegal with const or immutable, 
and allowing it would violate the type system. You need a way to just do _one_ 
copy rather than copy and then edit - so basically, you need a copy 
constructor.

Regardless, this is definitely one of the issues with const and immutable that 
needs to be fixed for them to be completely viable.

- Jonathan M Davis


More information about the Digitalmars-d mailing list