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

Tobias Pankrath tobias at pankrath.net
Wed Apr 3 08:25:21 PDT 2013


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.



More information about the Digitalmars-d-learn mailing list