On Sun, 15 Feb 2009 09:50:54 +0300, Eugene Y. <[email protected]> wrote:

class C
{
}

If I declare an instance of class C

C cinstance = new C();

is cinstance a pointer or is it like C++?
I'm wondering this because I tested with DMD 2.008 and if I do this

C dinstance = cinstance;

it doesn't seem to copy by value but by reference just like copying pointers
in C/C++.
If this is the case, is there any point in having pointers to Classes?

D distinguishes between value types (structs, similar to C/C++ POD types) and 
reference types (classes, similar to C++ pointer to classes). This is a modern 
design decision, shared by Java, C# and many other languages. It has some 
drawbacks but also has some advantages.

Generally classes are long living objects. As such, you often pass and return 
them from functions, which should be done by reference/via pointer anyway. You 
should try avoiding using classes as a temporary/intermediate variables, 
because classes are heap-allocated in most cases.

Use structs for such purposes. All structs are stack-allocated unless you 
heap-allocate them explicitly (Foo* foo = new Foo();).
Whenever you need class instance to be destroyed upon leaving current scope, you prepend 
a "scope" modifier in front of the variable definition:

scope Bar bar = new Bar();

Compiler will automatically destroy it at living the scope. As a bonus (an 
optimization) compiler will most likely allocate the class instance on stack.

You can't return scope objects from functions for obvious reasons.

Hope this helps. If you have any questions - ask away.

Reply via email to