Question

Does D have something similar to C++11's emplace_back()? I typically want this when I append a single or multiple structs to the end of an array or some other D container with value semantics on its members?

Update: I guess this is the answer right?: http://dlang.org/phobos/std_conv.html#.emplace

I still think its relevant to question the need for emplace regarding the fact that D has stricter control over memory - Could the need for emplace be made obselete through clever compiler optimization, in the case mentioned above?

Was it helpful?

Solution

D's emplace needs the memory to already be set up ahead of time and is primarily meant to be used to put classes on the stack or manually managed memory (the built-in new always uses the gc heap unless you hack the druntime).

emplace_back appends too. So to get what it does, you'd first append an element, then emplace it. But since D's classes are always references, that wouldn't really work without some care.

If you are appending structs to an array, that'd work in place, and I'm not sure if it copies or not. The compiler could certainly optimize that away:

struct A {}
A[] arr;
arr ~= A(); // this puts the new one at the end of the array, and might optimize away the copy

Appending a class in place to an array would be trickier. You'd want to do something alone these lines:

ubyte[] arr;
C[] references;

arr.length = arr.length + __traits(classInstanceSize, C);
references ~= emplace!(C)(arr[$ - __traits(classInstanceSize, C) .. $], ctor args...);

Or something like that. If you are using the object by value a lot though, or need more precise control over the memory, you should look into using structs instead. If possible, it will be a lot easier.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top