[swift-dev] Pointers vs. References?

John McCall rjmccall at apple.com
Mon Dec 14 14:35:28 CST 2015


> On Dec 14, 2015, at 11:43 AM, Jacob Bandes-Storch <jtbandes at gmail.com> wrote:
> I was thinking it might help some of the null-dereference issues if more things were to be passed as references. Is there a particular reason to use pointers instead? It seems there are several places which accept pointers and assume they're not null, which isn't really safe.

In principle, I agree, hence the design of Swift optionals.  However, C++ isn’t very cooperative here.  Compilers do a lot of dynamic casting, and to work idiomatically, the result of a dynamic cast needs to be something you can test in an if condition (an optional type, if you will).  However, C++ if conditions aren't "test-and-unwrap” like Swift’s if-let, they’re just “test”, so even within the guarded block you now need a lot of fussy (and only contextual safe) code to get back to a non-optional type that you can actually do something with.  It’s not really worth it.

> (And, there's probably some work to be done adding `const` in a bunch of places.)

My experience is that ‘const’ doesn’t provide much value with language representations.  There’s a lot of boilerplate and redundancy to overload operations to propagate const-ness around correctly, you inevitably end up const_cast’ing stuff all the time regardless, and it’s generally well-known whether a particular context has any business modifying the representation (usually: no).

John.


More information about the swift-dev mailing list