pointers, assignments, Garbage Collection Oh My?

H. S. Teoh hsteoh at quickfur.ath.cx
Wed Jul 10 11:44:23 PDT 2013


On Wed, Jul 10, 2013 at 08:38:40PM +0200, JohnnyK wrote:
[...]
> Reminds me of how Delphi (aka Pascal) strings are work.  Thanks
> everyone this answers some of my questions.  Now what about when the
> return type of a function is a string?  Is D returning the pointer
> to the string structure or is it returning the structure?

D structs are always passed by value, so it's the length+pointer pair
that's being returned. There's no extra indirection involved here. What
it points to stays where it is on the GC heap.

So for example:

	int[] data = [1,2,3];

	int[] f() {
		return data;
	}

	void main() {
		auto arr = f();	// returns copy of data's ptr+length
		arr.length--;	// modifies this copy
		assert(arr == [1,2]);
		assert(data == [1,2,3]); // data itself hasn't changed
	}

Does this help?


T

-- 
Be in denial for long enough, and one day you'll deny yourself of things you wish you hadn't.


More information about the Digitalmars-d-learn mailing list