Why can't I copy a const struct?

Ali Çehreli acehreli at yahoo.com
Fri Nov 15 10:37:45 PST 2013


The short answer to the question in the subject line is because D does 
not have copy constructors.

On 11/15/2013 07:12 AM, Atila Neves wrote:

 >      private struct DummyStruct {
 >          int[] a;
 >
 >          this(this) {
 >              a = a.dup;

That line can work only if a is mutable. The trouble is, the type of a 
is const(int[]) there.

 >          }
 >      }
 >
 >
 >      void main() {
 >          const dummy1 = DummyStruct();
 >          DummyStruct dummy2 = dummy1;
 >      }
 >
 >      struct_copy.d(12): Error: conversion error from const(DummyStruct)
 > to DummyStruct
 >
 > Surely I should be able to copy it and use the mutable version as I
 > please, no? I'd understand if the postblit constructor wasn't defined...

That makes sense but the compiler would not analyze the code and ensure 
that the code obeys const. (It probably can in most situations though.)

 > Atila

One workaround is a constructor that takes by ref const:

import std.stdio;

private struct DummyStruct {
     int[] a;

     this (int[] a) {
         this.a = a.dup;
     }

     this(ref const(DummyStruct) that) {
         writeln("copy");
         this.a = that.a.dup;
     }
}

void main() {
     const dummy1 = DummyStruct([ 1 ]);
     auto dummy2 = DummyStruct(dummy1);  // <-- note different syntax
     assert(dummy2.a.ptr != dummy1.a.ptr);
}

Ali



More information about the Digitalmars-d-learn mailing list