Memory management

IGotD- nise at nise.com
Tue Sep 29 16:03:39 UTC 2020


On Tuesday, 29 September 2020 at 15:47:09 UTC, Ali Çehreli wrote:
>
> I am not a language expert but I can't imagine how the compiler 
> knows whether an event will happen at runtime. Imagine a server 
> program allocates memory for a client. Let's say, that memory 
> will be deallocated when the client logs out or the server 
> times that client out. The compiler cannot know either of that 
> will ever happen, right?
>
> Ali

It doesn't need to know when a certain event happens but based on 
ownership and program flow. Let's think Rust for a moment.

You get a connection and you allocate some metadata about it. 
Then you put that metadata on a list and the list owns that 
object. It will stay there as long there is a connection and the 
program can go and do other things, the list still owns the 
metadata.

After a while the client disconnects and the program finds the 
metadata in the list and removes it and puts it in a local 
variable. Some cleanup is one but the metadata is still owned by 
the local variable and when that variable goes out of scope 
(basically end of a {} block), then it will deallocated.

It's really a combination of ownership and scopes.

That little simple example shows that you don't necessarily need 
to know things in advance in order to have static lifetimes. 
However, there are examples where there is no possibility for the 
compiler to infer when the object goes out of scope. Multiple 
ownership is an obvious example of that.




More information about the Digitalmars-d-learn mailing list