Defining a custom *constructor* (not initializer!)

Mehrdad wfunction at hotmail.com
Fri May 11 16:43:48 PDT 2012


On Friday, 11 May 2012 at 22:28:55 UTC, Jacob Carlborg wrote:
> On 2012-05-06 21:55, Mehrdad wrote:
>> Is this possible in D2?
>>
>> i.e. I'm wondering if there is a way to do the object
>> construction yourself, which would allow you to call the 
>> object's
>> "constructor" (initializer) manually, and just return a pointer
>> to the new object.
>>
>> Something along the lines of:
>>
>> class Window
>> {
>> static Window opConstruct(void* ptr)
>> {
>> // Assume ptr is already correctly sized and filled
>> Window result = cast(Window)ptr;
>> result.__ctor();
>> return return result;
>> }
>> }
>>
>> It seems like overloading new() *almost* does this, but not
>> quite: It only lets you allocate the memory, not call the
>> constructor yourself.
>>
>> This would be useful, because some objects can have external
>> constructors (notably when interfacing with C/C++, such as when
>> using CreateWindow() in Windows), and you *cannot* call these
>> constructors inside the object's "constructor" (initializer) 
>> due
>> to re-entrancy issues.
>
> Don't know if it helps but, have a look the DWT sources:
>
> https://github.com/d-widget-toolkit/org.eclipse.swt.win32.win32.x86/tree/master/src/org/eclipse/swt
>
> should probably be in the internal folder, widgets/Widget or 
> widgets/Shell.


Thanks for the link.
It seems like it's on Control.d...

Yup, they do what C# does with the constructor: they put make a 
*separate* function, createHandle(), used to create the control.

And they simply *don't* tie the destructor to DestroyWindow(); 
instead, they just assume the user will call dispose().

So in other words, they just ignored the entire problem with the 
lifetimes, and hoped ("required"?) that the user will call 
dispose().

Not something I'd want to do, since (even according to .NET's 
philosophy) a handle leak must NEVER occur, as long as the 
program has control, even if the user doesn't dispose the object.

The closing of the handle can of course be nondeterministic due 
to the GC, but it must be eventually cleaned up when the object 
is GC'd.


Any ideas if this would be easy/hard to add to DMD/Phobos?


More information about the Digitalmars-d mailing list