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

kenji hara k.hara.pg at gmail.com
Sat Nov 12 07:22:53 PST 2011


Here is a pitfall.
If S has the postblit, it is not called with your code.

import core.stdc.stdio;
struct S
{
    this(this){
        printf("postblit\n");
    }
}
void main()
{
    S s;
    S* ps = [s].ptr;
    // does not print "postblit"
}

I've already poted a pull
(https://github.com/D-Programming-Language/dmd/pull/375) to fix it,
but it is not yet merged.

A workaround is follows.

// The definition of S is same as above.
T makecopy(T)(ref T obj) if (is(T == struct))
{
    auto dup = obj;  // make copy with calling postblit
    return dup;
}
void main()
{
    S s;
    S* ps = [makecopy(s)].ptr;
    // print "postblit"
}

If you use it, please be careful.

Kenji Hara.

2011/11/13 Timon Gehr <timon.gehr at gmx.ch>:
> 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