Defining a custom *constructor* (not initializer!)

Mehrdad wfunction at hotmail.com
Sun May 6 12:55:29 PDT 2012


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.


More information about the Digitalmars-d mailing list