www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - safety of move

reply Ellery Newcomer <ellery-newcomer utulsa.edu> writes:
I find myself using [abusing?] move lately:

import std.algorithm;
import std.stdio;

struct A {
     const(int) i;
     int j;
     int k;
}

void main() {
     A* a = new A(); // pretend this is malloc or something
     // *a = A(1)
     A a2 = A(1);
     move(a2, *a);

     A[] arr = new A[](2);
     //arr[1] = *a;
     move(*a, arr[1]);
}

For the first part, I have a A* pointing to uninitialized memory and I 
need to initialize it somehow. move works I guess because it uses memcpy 
or something. Not complaining, but wondering.

The second part violates D's const semantics and maybe shouldn't be 
permitted. But it is.
Nov 27 2012
parent Dmitry Olshansky <dmitry.olsh gmail.com> writes:
11/28/2012 7:19 AM, Ellery Newcomer пишет:
 I find myself using [abusing?] move lately:

 import std.algorithm;
 import std.stdio;

 struct A {
      const(int) i;
      int j;
      int k;
 }

 void main() {
      A* a = new A(); // pretend this is malloc or something
      // *a = A(1)
      A a2 = A(1);
      move(a2, *a);

      A[] arr = new A[](2);
      //arr[1] = *a;
      move(*a, arr[1]);
 }

 For the first part, I have a A* pointing to uninitialized memory and I
 need to initialize it somehow.
emplace should work for constructing A in a given chunk of memory.
 move works I guess because it uses memcpy
 or something. Not complaining, but wondering.
Yes it hacks through const/immutable at ease. The only requirement seems that it has to be shallow immutable/cont.
 The second part violates D's const semantics and maybe shouldn't be
 permitted. But it is.
I agree. -- Dmitry Olshansky
Nov 28 2012