digitalmars.D.learn - struct on heap with std.experimental.allocator
- jmh530 (24/24) Jun 07 2016 I modified one of the first examples from
- Adam D. Ruppe (9/11) Jun 07 2016 It doesn't matter what heap it is on, you are just using a
- jmh530 (2/13) Jun 07 2016 Thanks for the reply!
I modified one of the first examples from
std.experimental.allocator to put a struct on the heap (below).
My sense is that putting it on the GC heap gives the struct
reference semantics. I was struck by two things. First, I didn't
have to use (*a).x, I could just use a.x. Also, when I assign a
struct object to another instance, changes in the new one also
effect the original.
import std.experimental.allocator;
struct A
{
int x;
}
void main()
{
A* a = theAllocator.make!A(42);
assert((*a).x == 42);
assert(a.x == 42);
auto b = a;
assert(b.x == 42);
++b.x;
assert(b.x == 43);
assert(a.x == 43);
}
Jun 07 2016
On Tuesday, 7 June 2016 at 15:39:59 UTC, jmh530 wrote:My sense is that putting it on the GC heap gives the struct reference semantics.It doesn't matter what heap it is on, you are just using a pointer here. Struct pointers in D will automatically dereference with a.x, so no need for the * there (in most cases), and assigning it to another pointer of course still points to the same object, so it will affect both. If you want a copy, you can use a special method to allocate a new one or use auto a = *b; which will copy it to the stack.
Jun 07 2016
On Tuesday, 7 June 2016 at 15:43:34 UTC, Adam D. Ruppe wrote:On Tuesday, 7 June 2016 at 15:39:59 UTC, jmh530 wrote:Thanks for the reply!My sense is that putting it on the GC heap gives the struct reference semantics.It doesn't matter what heap it is on, you are just using a pointer here. Struct pointers in D will automatically dereference with a.x, so no need for the * there (in most cases), and assigning it to another pointer of course still points to the same object, so it will affect both. If you want a copy, you can use a special method to allocate a new one or use auto a = *b; which will copy it to the stack.
Jun 07 2016








jmh530 <john.michael.hall gmail.com>