GC for noobs

Dicebot public at dicebot.lv
Thu Feb 27 07:01:53 PST 2014


On Thursday, 27 February 2014 at 14:49:48 UTC, Szymon Gatner 
wrote:
>> You can disable postblit to make entity non-copyable: 
>> http://dlang.org/struct.html#StructPostblit
>
> How can I then use it as a function return value? Or store in a 
> container?
>
> Actually if postblit had a bool param saying that the source is 
> rvalue then moving would be possible by just resetting relevant 
> fields in source object.

Yep, moving ownership is the main issue (as opposed to just 
prohibiting any copy). But returning from function is not copying 
because of D semantics and you can do some tricks because of it:

http://dpaste.dzfl.pl/99ca668a1a8d

==================================

import std.c.stdlib;

struct Unique
{
	int* data;
	
	@disable this(this);
	
	~this()
	{
		if (data)
			free(data);
	}
	
	Unique release()
	{
		scope(exit) this.data = null;
		return Unique(data);
	}
}

void main()
{
	Unique x1 = Unique(cast(int*) malloc(int.sizeof));
	
	// auto x2 = x1; // error
	auto x2 = x1.release();
	assert(x1.data is null);
	assert(x2.data !is null);
}


More information about the Digitalmars-d-learn mailing list