operator new(): struct v. class

Kirk McDonald kirklin.mcdonald at gmail.com
Fri Aug 17 15:39:18 PDT 2007


C. Dunn wrote:
> Walter, could you please address this?  I have no problem at all with your design decisions.  All I want is an operator New() that the compiler will understand, and which allows me to compare the performance of struct pointers to classes.
> 
> I have outlined the issue below:
> 
> 
> Walter Bright Wrote:
> 
> 
>>James Dennett wrote:
>>
>>>Walter Bright wrote:
>>>
>>>>Value types are fundamentally different from reference types. D gives
>>>>you the choice.
>>>
>>>C++ gives you *more* choice by allowing easier migration between
>>>the two without imposing performance or syntactic differences.
>>
>>That isn't my experience. In my work on DMDscript in D, I changed some
>>types between struct and class to try out some variations, and found it
>>to be a lot easier than in C++. For one thing, I didn't have to find and
>>edit all the -> and .'s.
> 
> 
> 
> But Walter, how did you handle operator new()?  It needs to be agnostic about class/struct.
> 
> class C{int x;};
> stuct S{int x;};
> typedef C MyType;
> //typedef S* MyType;
> MyType inst = new MyType;
> 
> If you use the second typedef, this will not compile!  That is the problem.
> 
> Why not provide an operator New() which expects a pointer type when used for structs?  Just have the compiler translate it.  I cannot see how to write such a generic operator New() myself.
> 
> This one small change would be a great boon to any C/C++ programmer thinking of adopting D.

It's a trivial bit of template code. Something like this:

T New(T)() {
	static if (is(T U == U*)) {
		return new U;
	} else {
		return new T;
	}
}

class C {}
struct S {}

void main() {
	C c = New!(C);
	S* s = New!(S*);
}

Handling constructor arguments, too, is only a little more complicated.

-- 
Kirk McDonald
http://kirkmcdonald.blogspot.com
Pyd: Connecting D and Python
http://pyd.dsource.org



More information about the Digitalmars-d mailing list