[Dlang-study] [lifetime] destructor, difference between C++ and D and rationale

Andrei Alexandrescu andrei at erdani.com
Thu Oct 29 05:39:24 PDT 2015


On 10/28/2015 08:29 PM, deadal nix wrote:
> I think it is very relevent here as destructor is a very common tool to
> free resources, as well as one of the most complex to deal with, mostly
> because of move semantic. I already had in mind to launch that subject
> before this whole thing started.
>
> Why were things changed that way ?

On second thought this might inform the best way to go about assigning 
responsibility for inc/decref across the caller and callee.

Regarding object copying: we noticed that in C++ it's difficult to 
define efficient move semantics and forwarding. This is because in a 
call line

fun(string("hello"));

even if fun "consumes" the string by either returning it or forwarding 
it to another function, the caller of fun must still destroy the rvalue 
created. In C++1x, if move semantics are at work, there's still a need 
for the callee to leave the moved-from string in a well-defined state so 
the destructor doesn't crash. All of that work is unneeded and is 
required for the sake of that destructor call.

In D a key element is that objects are relocatable, i.e. they can be 
moved across memory by using memcpy(). That makes it a more efficient 
protocol possible:

1. Caller calls the constructor
2. Object is bibblitted around
3. Object gets destroyed

So in D, perfect forwarding comes for "free" and we don't need a large 
feature such as C++'s rvalue references.

The disadvantage is you can't have value objects with internal pointers. 
(You can still have reference objects with internal pointers.)


Andrei


More information about the Dlang-study mailing list