How do you deal with scoped allocations?

John Colvin john.loughran.colvin at gmail.com
Sun Dec 8 01:21:50 PST 2013


On Saturday, 7 December 2013 at 22:32:59 UTC, Namespace wrote:
> Since my last thread doesn't get much attention I like to ask 
> here: How did you deal with temporary memory? Let's assume that 
> the size is only known at runtime.
> I have this situation e.g. in Dgame in the capture method: I 
> get the pixel data from my Window with glReadPixel but it is 
> reversed. So I have to reverse it again, but I still need at 
> least temporary memory for one pixel-line which stores the 
> currently swapped pixels. So how would you solve such a 
> situation?
>
> Since D doesn't offer VLA's and alloca is broken (besides the 
> ugly syntax),
> I use a scoped wrapper (since scope doesn't do the job):
>
> ----
> struct scoped(A : T[], T) {
> 	T[] arr;
>
> 	alias arr this;
>
> 	this(T[] arr) {
> 		this.arr = arr;
>
> 		writefln("Get %d %s's (ptr = %x)", arr.length, T.stringof, 
> arr.ptr);
> 	}
>
> 	~this() {
> 		GC.free(this.arr.ptr);
> 		this.arr = null;
> 		GC.minimize();
> 	}
> }
>
> void main() {
>     // need temp memory
>     scoped!(int[]) arr = new int[n];
> }
> ----
>
> And what do you use?


 From my probably somewhat incomplete understanding of such things:
This is not a good use-case for the gc. Use the c heap or just 
let the gc do its job normally.


More information about the Digitalmars-d mailing list