Paralysis of analysis

Steven Schveighoffer schveiguy at yahoo.com
Wed Dec 15 12:36:00 PST 2010


On Wed, 15 Dec 2010 15:19:34 -0500, Dmitry Olshansky  
<dmitry.olsh at gmail.com> wrote:

> On 15.12.2010 22:52, Steven Schveighoffer wrote:
>> On Wed, 15 Dec 2010 14:18:20 -0500, Dmitry Olshansky  
>> <dmitry.olsh at gmail.com> wrote:
>>> Hm,
>>> ((T*)malloc(1024*T.sizeof))[0..size];
>>> works. Just needs careful initialization of each field, since they are  
>>> filled with trash ...
>>> And you can even do slicing. Just don't append to them and keep track  
>>> of the initial reference ;)
>>
>> You can append them.  The append code will recognize that it's not a GC  
>> block and reallocate.
>
> Good to know.

I should also note, if you do this:

auto x = ((T*)malloc(1024*T.sizeof))[0..size];
x ~= T.init;

You have now lost the original reference to the data (because x now points  
to the GC allocated block), so it will leak!  So while appending does  
work, you have to take care to still keep track of the original data.  I'd  
recommend something like this if it's a temporary:

auto x = (cast(T*)malloc(1024*T.sizeof))[0..size];
const origdata = x.ptr;
scope(exit) free(origdata);

-Steve


More information about the Digitalmars-d mailing list