Is it bad practice to alter dynamic arrays that have references to them?

simendsjo simen.endsjo at pandavre.com
Thu Aug 5 12:23:13 PDT 2010


On 05.08.2010 20:50, Steven Schveighoffer wrote:
> On Thu, 05 Aug 2010 14:41:12 -0400, simendsjo
> <simen.endsjo at pandavre.com> wrote:
>
>> On 05.08.2010 19:35, Steven Schveighoffer wrote:
>>> On Thu, 05 Aug 2010 13:10:44 -0400, simendsjo
>>> <simen.endsjo at pandavre.com> wrote:
>> (...)
>>>
(...)
>> Ah, that's really good to know! So I can see if it will reallocate using
>> bool willReallocate = array.capacity < (array.length +
>> numberOfItemsToAppend)
>> ?
>
> Yes, except the condition should be <=. And that function is
> implementation independent (the value returned isn't, but it's
> guaranteed that willReallocate should reflect whether the runtime will
> reallocate)
>
	bool willReallocate(T)(T[] array, T[] toAppend) {
		return array.capacity < (array.length + toAppend.length);
	}
	
	int[] a = [0];
	auto aOldPtr = a.ptr;
	assert(a.capacity == 3);
	
	// a.length == a.capacity, so no reallocation
	int[] b = [1,2];
	assert(!willReallocate(a, b));
	a ~= b;
	assert(a.ptr == aOldPtr);
	
	// c.length == 0, so still no
	int[] c;
	assert(!willReallocate(a, c));
	a ~= c;
	assert(a.ptr == aOldPtr);
	
	// there, a.length > a.capacity and reallocation
	int[] d = [3];
	assert(willReallocate(a, d));
	a ~= d;
	assert(a.ptr != aOldPtr);




More information about the Digitalmars-d-learn mailing list