Smart pointers instead of GC?

Michel Fortin michel.fortin at michelf.ca
Mon Feb 3 20:17:06 PST 2014


On 2014-02-04 03:45:53 +0000, Walter Bright <newshound2 at digitalmars.com> said:

> On 2/3/2014 7:24 PM, Michel Fortin wrote:
>> But, you could implement this as a template function if you absolutely need to
>> transfer nullability, and the template will actually make things more efficient
>> because the template instantiated with a non-nullable function argument will
>> optimize away the unnecessary branch.
> 
> Yes, you could use a template, but the idea was to avoid bloat in the 
> executable by having multiple sets of functions that differ only by 
> their mangled name. Furthermore, templates cannot be used to create 
> virtual functions.

Unlike with the mutable/const/immutable case, those templates actually 
won't only differ only by their mangled names, because any check for 
null will be quashed by the optimizer in the not-null variant.

You can write two function if you really need them to be virtual, but 
as explained below I doubt you'll need to do that anyway.

>> And to get to the root of this, I think it'd be much more useful to 
>> have a "same
>> type as input" stand-in, because notice how in the above function if you pass a
>> DerivedObject, you'll get an Object returned, losing the derived part? Exact
>> same problem, and we've been living with it for decades.
> 
> The const issue is a recurring theme in a lot of C++ code, the derived 
> type one just doesn't seem to come up.
> 
> Also, what is being looked at to transfer is the qualifier, not the 
> type, as the type may actually change (such as returning a pointer to a 
> field of the argument).

Yes, but const in C++ applies to all the fields of an aggregate. Making 
a struct variable const means all its fields are seen as const. To 
write accessors that works with both const and non-const you need to 
duplicate each of them.

That's not the case for nullable. Fields do not become nullable because 
the pointer leading to the struct is nullable. You only have to write 
one accessor that takes a non-nullable pointer or ref, and let the 
parent context make sure it is not nullable before calling it. Even 
today, most accessors don't check "this" for null anyway, so we're just 
formalizing that contract and enforcing it statically.

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



More information about the Digitalmars-d mailing list