www.digitalmars.com         C & C++   DMDScript  

digitalmars.D - Copy constructor in D. Why it is necessary to have it.

reply Eldar Insafutdinov <e.insafutdinov gmail.com> writes:
http://www.everfall.com/paste/id.php?m46jrb36o7qu

This is a short example. It has all the comments inside. Since "in" keyword
tells the compiler to make a copy of an class object - a new object is created.
But constructor for this object is not called(you can check it). In my opinion
it is a big issue and needs to be improved.
Sep 30 2008
parent "Denis Koroskin" <2korden gmail.com> writes:
On Tue, 30 Sep 2008 23:37:50 +0400, Eldar Insafutdinov  
<e.insafutdinov gmail.com> wrote:

 http://www.everfall.com/paste/id.php?m46jrb36o7qu

 This is a short example. It has all the comments inside. Since "in"  
 keyword tells the compiler to make a copy of an class object - a new  
 object is created.

No, that's not true. No heap activity is done under the hood, a copy of /pointer/ is passed (as opposed to a copy of /instance/). In means that changes to the variable won't be visible to the caller: void foo(in TreeIter it) { it = null; // makes local change } An important thing to note is that `in` is not recursive (as const or invariant).
 But constructor for this object is not called(you can check it). In my  
 opinion it is a big issue and needs to be improved.

No, it shouldn't generate heap activity unless really needed. In this case do the following: void foo(const(TreeIter) it) { auto itCopy = it.clone(); // do whatever you wish with a copy. } But in general, a const reference should be enough to you.
Sep 30 2008