www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - struct on heap with std.experimental.allocator

reply jmh530 <john.michael.hall gmail.com> writes:
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
parent reply Adam D. Ruppe <destructionator gmail.com> writes:
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
parent jmh530 <john.michael.hall gmail.com> writes:
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:
 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.
Thanks for the reply!
Jun 07 2016