1

Does Dart provide any form of memcpy-like functions? I'd like to do a shallow copy of one object's data to the address of another:

var foo = Foo("hi");
var bar = Foo("hello");

memcpy(&foo, &bar, sizeof(Foo)); 
Basic Coder
  • 10,882
  • 6
  • 42
  • 75
  • 2
    I think you cannot regarding this answer :/ https://stackoverflow.com/questions/13107906/how-can-i-clone-an-object-deep-copy-in-dart – M0ustach3 May 18 '20 at 06:45
  • That question is about deep copy. What part of it answers this question? – Mawg says reinstate Monica May 18 '20 at 06:47
  • Dart does not have a function to copy objects (deep or shallow) unless this feature has been implemented manually for each class. E.g. List's support shallow copies where you can create a new list object containing the same object instances as the original list. – julemand101 May 18 '20 at 07:25

1 Answers1

2

No.

Dart does not allow you access to memory as such, and it has no way to shallow-copy an object without the class cooperating.

If you want to copy an object, you must create a new object using a constructor and have it fill in the fields. Dart constructors can do anything, and some classes are built in a way where they depend on a constructor maintaining some coherent global state. For example, a class could assign consecutive IDs to its objects by initializing a field with final int id = _staticCounter++;. Copying that object would break the invariant that all objects have different IDs.

There is no known workaround for a shallow copy.

For a deep copy, there is one hack that gets around this. If your platform supports dart:isolate, you can send an object to yourself:

import "dart:mirrors";
Future<T> clone<T>(T value) {
  return (ReceivePort()..sendPort.send(value)).first;
}

Not all values can be sent through a send-port. Not all classes will work correctly for objects not created using constructors.

lrn
  • 64,680
  • 7
  • 105
  • 121