How to allocate an element of type T with value x in generic code?

John Colvin john.loughran.colvin at gmail.com
Wed Apr 3 08:53:08 PDT 2013


On Wednesday, 3 April 2013 at 15:25:22 UTC, Tobias Pankrath wrote:
> On Wednesday, 3 April 2013 at 14:47:22 UTC, John Colvin wrote:
>> On Wednesday, 3 April 2013 at 11:05:06 UTC, Tobias Pankrath 
>> wrote:
>>> basic idea.
>>> ---
>>> T x;
>>> T* px = new T(x);
>>> ---
>>> int x
>>> int* px = new int(x); // fails
>>> ---
>>>
>>> I need to do this for structs and basic types. What's the 
>>> standard way to do this?
>>
>> Do you need to use new? i.e. do you need the variable to be 
>> allocated on the heap?
>> Also, as you've written it, px is not a pointer to x which is 
>> a bit misleading. What is the result you actually want?
>
> I need a fresh T (let's call it t) allocated on the heap and a 
> pointer (pt) to it and the value of t should be the value of x.
>
> ---
> T x;
> int* pt = new T;
> *pt = x;
> ---
>
> Maybe I'll just do this.

int* pt = new T; //that will only compile if T is int. I assume 
you meant:
T* pt = new T;

Other than that, what you have done there should work.

To avoid any superfluous initialisation of fields:

import core.memory : malloc;
T x;

T* pt = cast(T*)malloc(T.sizeof);
*pt = x;

note: this is not C malloc, the memory is requested from and 
managed by the GC.


More information about the Digitalmars-d-learn mailing list