DIP 1018--The Copy Constructor--Formal Review

Andrei Alexandrescu SeeWebsiteForEmail at erdani.org
Thu Feb 28 01:42:13 UTC 2019


On 02/25/2019 03:41 PM, Paolo Invernizzi wrote:
> On Monday, 25 February 2019 at 20:23:58 UTC, Andrei Alexandrescu wrote:
>> On 2/25/19 3:23 PM, Jacob Carlborg wrote:
>>> On 2019-02-25 20:24, Mike Parker wrote:
>>>
>>>>  From the process document:
>>>>
>>>> “the DIP Manager or the Language Maintainers may allow for
>>>> exceptions which waive requirements or responsibilities at their
>>>> discretion.”
>>>
>>> Having it documented doesn't make it less flawed.
>>
>> Jacob, are there amends you need to make to the DIP?
>
> Honestly, I've not understood the rationale or the covered use case in
> letting the copy ctor mutate the ref source parameters...
> Sincerely, without polemical intent.

I made an editorial pass:

https://github.com/dlang/DIPs/pull/145

The most material change was additional explanation of using mutable ref 
instead of e.g. const. Here's the relevant excerpt, please let me know 
if it clarifies the motivation.

=============================================
1. The parameter of the copy constructor is passed by a mutable 
reference to the
source object. This means that a call to the copy constructor may 
legally modify
the source object:

```d
struct A
{
     int[] a;
     this(ref A another)
     {
         another.a[2] = 3;
     }
}

void main()
{
     A a, b;
     a = b;    // b.a[2] is modified
}
```

This is surprising and potentially error-prone behavior because changing 
the source of a copy is not customary and may surprise the user of a 
type. (For that reason, C++ coding standards adopt the convention of 
taking the source by means of reference to `const`; copy constructors 
that use non-`const` right-hand side are allowed but discouraged.) In D, 
`const` and `immutable` are more restrictive than in C++, so forcing 
`const` on the copy constructor's right-hand side would make simple 
copying task unduly difficult. Consider:

```d
class Window
{
     ...
}
struct Widget
{
     private Window display;
     ...
     this(ref const Widget rhs)
     {
         display = rhs.display; // Error! Cannot initialize a Window 
from a const(Window)
     }
}
```

Such sharing of resources across objects is a common occurrence, which 
would be impeded by forcing `const` on the right-hand side of a copy. 
(An inferior workaround would be to selectively cast `const` away inside 
the copy constructor, which is obviously undesirable.) For that reason 
this DIP proposes allowing mutable copy sources.
=============================================



More information about the Digitalmars-d-announce mailing list