DIP77 - Fix unsafe RC pass by 'ref'

Michel Fortin via Digitalmars-d digitalmars-d at puremagic.com
Thu Apr 9 05:05:16 PDT 2015


On 2015-04-08 23:10:37 +0000, Walter Bright <newshound2 at digitalmars.com> said:

> http://wiki.dlang.org/DIP77

In the definition of a Reference Counted Object:

"""
An object is assumed to be reference counted if it has a postblit and a 
destructor, and does not have an opAssign marked @system.
"""

Why should it not have an opAssign marked @system?

And what happens if the struct has a postblit but it is @disabled? Will 
the compiler forbid you from passing it by ref in cases where it'd need 
to make a copy, or will it just not be a RCO?

More generally, is it right to add implicit copying just because a 
struct has a postblit and a destructor? If someone implemented a 
by-value container in D (such as those found in C++), this behaviour of 
the compiler would trash the performance by silently doing useless 
unnecessary copies. You won't even get memory-safety as a benefit: if 
the container allocates from the GC it's safe anyway, otherwise you're 
referencing deallocated memory with your ref parameter (copying the 
struct would just make a copy elsewhere, not retain the memory of the 
original).

I think you're assuming too much from the presence of a postblit and a 
destructor. This implicit copy behaviour should not be trigged by 
seemingly unrelated clues. Instead of doing that:

	auto tmp = rc;

the compiler should insert this:

	auto tmp = rc.opPin();

RCArray can implement opPin by returning a copy of itself. A by-value 
container can implement opPin by returning a dummy struct that retains 
the container's memory until the dummy struct's destructor is called. 
Alternatively someone could make a dummy "void opPin() @system {}" to 
signal it isn't safe to pass internal references around (only in system 
code would the implicit call to opPin compile). If you were writing a 
layout-compatible D version of std::vector, you'd likely have to use a 
@system opPin because there's no way you can "pin" that memory and 
guaranty memory-safety when passing references around.

-- 
Michel Fortin
michel.fortin at michelf.ca
http://michelf.ca



More information about the Digitalmars-d mailing list