[Issue 1860] New: Heap construction of structs with args doesn't work

downs default_357-line at yahoo.de
Thu Feb 21 22:42:50 PST 2008


downs wrote:
> Try this.
> 
> import std.gc;
> struct heapmalloc(T) {
> 	static T* opCall(U...)(U u) {
> 		auto res = cast(T*) malloc(T.sizeof);
> 		(*res) = T(u);
> 		return res;
> 	}
> }
> 
> 
> struct Foo {
> 	int a;
> 	float b;
> }
> 
> void main() {
> 	auto heapfoo = heapmalloc!(Foo)(1984, 3.14159);
> }

Or this.

import std.gc;

T* toHeap(T)(T st) {
        auto res = cast(T*) malloc(T.sizeof);
        (*res) = st;
        return res;
}


struct Foo {
        int a;
        float b;
}

void main() { auto th = toHeap(Foo(1984, 3.1415926)); assert(th.a == 1984); }

:)

 --downs


More information about the Digitalmars-d-bugs mailing list