Consistency, Templates, Constructors, and D3
David Piepgrass
qwertie256 at gmail.com
Tue Aug 28 13:25:43 PDT 2012
On Monday, 27 August 2012 at 20:22:47 UTC, Era Scarecrow wrote:
> On Monday, 27 August 2012 at 14:53:57 UTC, F i L wrote:
>> in C#, you use 'new Type()' for both classes and structs, and
>> it works fine. In fact, it has some benefit with generic
>> programming. Plus, it's impossible to completely get away from
>> having to understand the type, even in C++/D today, because we
>> can always make factory functions:
>
> I'm sure in C# that all structs and classes are heap allocated
> (It takes after C++ very likely) that's the simplest way to do
> it. You can do that in C++ as well, but other than having to
> declare it a pointer first. In C++ they made structs 'classes
> that are public by default' by it's definition I believe.
> Considering how C++ is set up that makes perfect sense.
You're mistaken as FiL pointed out. "new" is simply not a heap
allocation operator in C#, it is a creation operator. Structs in
C# are allocated on the stack or embedded in another object (on
the stack or on the heap). "new X()" creates a new value of type
X, which could be a struct on the stack or a class on the heap.
I like the way C# works in this regard because the way X is
allocated is an implementation detail that is hidden from
clients. If the type X is immutable, then I can freely change it
from struct to class or vice versa without affecting clients that
use X. (Mind you if X is mutable, the difference is visible to
clients since x1 = x2 copies X itself, not a reference to X.)
Plus as mentioned, generic code can use "new T()" without caring
what kind of type T is.
More information about the Digitalmars-d
mailing list