More on C++ stack arrays

Namespace rswhite4 at googlemail.com
Wed Nov 6 08:52:44 PST 2013


On Wednesday, 23 October 2013 at 15:19:46 UTC, Namespace wrote:
>> can't you remove the if(this.ptr is null) return; checks 
>> everywhere - how should that happen - without exception at 
>> creation time
>
> Yes, this is somehow true. Here, the adjusted version.
> http://dpaste.dzfl.pl/e4dcc2ea

What if D would support variable-sized stack-allocated arrays 
through syntax sugar?
----
int n = 128;
int[n] arr;
----
would be rewritten with:
----
int n = 128;
int* __tmpptr = Type!int[n];
scope(exit) Type!int.deallocate(__tmpptr);
int[] arr = __tmpptr[0 .. n];
----

Where 'Type' is a struct like that:
----
struct Type(T) {
	static {
		enum Limit = 4096;

		void[Limit] _buffer = void;
		size_t _bufferLength;
	}

	static void deallocate(ref T* ptr) {
		.free(ptr);
		ptr = null;
	}

	static T* opIndex(size_t N) {
		if ((this._bufferLength + N) <= Limit) {
			scope(exit) this._bufferLength += N;

			return cast(T*)(&this._buffer[this._bufferLength]);
		}

		return cast(T*) .malloc(N * T.sizeof);
	}
}
----
which could be placed in std.typecons.

I think this should be easy to implement. What do you think?


More information about the Digitalmars-d mailing list