Copy a struct on the heap and get the pointer to it.

Timon Gehr timon.gehr at gmx.ch
Sat Nov 12 07:02:28 PST 2011


On 11/12/2011 03:39 PM, deadalnix wrote:
> Hi all,
>
> We recently had a discution on #D about copying a struct on the heap and
> getting a pointer to it.
>
> We come up with the following solution (Thanks to CyberShadow !) :
>
> struct S;
> S s; // Allocated locally.
> [s].ptr; // Get a pointer to a copy in the heap of the struct
>
> What is going on ? An array of one object is allocated on the heap and
> the struct copied in it. Then we get a pointer to the first (and only
> one) element of the array with ptr.
>
> So we have a pointer to a copy of s on the heap.
>
> I have several question on that :
> - Does a idiomatic way to do that exists ?

I don't think that this is such a common need.

> - Is this intented to do so ?

Yes.

> Will this construct risk to be broken in a
> future version of D ?

No.

> - Is this construct the idiomatic way to do so ?

It is certainly the most elegant way to do so.


More information about the Digitalmars-d mailing list