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

downs default_357-line at yahoo.de
Thu Feb 21 22:44:59 PST 2008


downs wrote:
> 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

Or this!

template heap() {
        import std.gc;
        typeof(this) heap() {
                auto res = cast(typeof(this)) malloc(typeof(*this).sizeof);
                (*res) = *this;
                return res;
        }
}

struct Foo {
        int a;
        float b;
        mixin heap!();
}

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


More information about the Digitalmars-d-bugs mailing list