Why do immutable variables need reference counting?

IGotD- nise at nise.com
Mon Apr 11 08:53:48 UTC 2022


On Sunday, 10 April 2022 at 23:19:47 UTC, rikki cattermole wrote:
>
> immutable isn't tied to lifetime semantics.
>
> It only says that this memory will never be modified by anyone 
> during its lifetime.
>
> Anyway, the real problem is with const. Both mutable and 
> immutable become it automatically.

I was thinking about that, often when using const you use it when 
passing parameters to functions. This is essentially borrowing. 
The situation is similar with C++ with unique_ptr and shared_ptr. 
Often C++ interfaces use const* when using pointers and not their 
smart pointer counterparts, so essentially the ownership remains, 
while "borrowing" are using raw pointers. A C++ interface only 
accepts the smart pointers when you want to change ownership. D 
could use a similar approach, when using pointers/references you 
shouldn't alter the internal data including reference count.

What I would interested in is if D could have move by default 
depending on type. In this case the RC pointer wrapper could be 
move by default. Increasing is only done when calling "clone" 
(similar to Rust). This way RC increases are optimized naturally. 
What I don't want from Rust is the runtime aliasing check 
(RefCell) on at all times. I rather go with that the compiler 
assumes no aliasing but the programmer is responsible for this. 
You can have runtime aliasing/borrowing check in debug mode but 
in release build it can be removed. This is similar to bounds 
checking where you can choose to have it or not.


More information about the Digitalmars-d-learn mailing list