www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Pointers

reply Eugene Y. <yes9111 gmail.com> writes:
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?
Feb 14 2009
next sibling parent Chris Nicholson-Sauls <ibisbasenji gmail.com> writes:
Eugene Y. 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
It is a reference. I'm not sure off the top of my head whether its a direct pointer or a handle under the hood, but at any rate, its a pointer to something.
 C dinstance = cinstance;
 
 it doesn't seem to copy by value but by reference just like copying pointers
 in C/C++.
Correct, it only copies the reference/pointer.
 If this is the case, is there any point in having pointers to Classes?
Not in the common case, no, but it can be useful at times. (Although, most of the cases where I would use them involve parameter passing, so I just use 'ref' arguments.) -- Chris Nicholson-Sauls
Feb 14 2009
prev sibling parent "Denis Koroskin" <2korden gmail.com> writes:
On Sun, 15 Feb 2009 09:50:54 +0300, Eugene Y. <yes9111 gmail.com> 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 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.
Feb 15 2009