[swift-evolution] Pitch: Deinit for structs

Joe Groff jgroff at apple.com
Wed Dec 23 17:25:54 CST 2015


> On Dec 23, 2015, at 3:16 PM, Matthew Johnson <matthew at anandabits.com> wrote:
> 
> 
> 
> Sent from my iPad
> 
>> On Dec 23, 2015, at 3:15 PM, Joe Groff via swift-evolution <swift-evolution at swift.org> wrote:
>> 
>> 
>>> On Dec 23, 2015, at 1:07 PM, Charles Srstka via swift-evolution <swift-evolution at swift.org> wrote:
>>> 
>>> Introduction:
>>> 
>>> This is a rather simple proposal, requesting that structs allow the ‘deinit’ destructor, as classes currently do.
>>> 
>>> Motivation:
>>> 
>>> Sometimes it is necessary to create an object that wraps a network connection (that needs to be closed when the object is destroyed), or that writes to a file on the disk (that has to be closed when the object is destroyed). Often these objects will implement a close() method, but in the case that the user forgets to call this before the object is disposed of, it is good to call it in deinit just in case. However, deinit currently is available only to classes and not to structs. This means that value types currently cannot be used for network and file-backed constructs. Given Swift’s emphasis on value types, it seems that it would be good to add this functionality to value types.
>> 
>> Network and file-backed constructs naturally have identity, so classes are appropriate. What benefit would you get from making them structs? What does it mean to copy a socket?
>> 
> 
> I wonder if the goal is to avoid a heap allocation.  Under what circumstances can stack promotion be guaranteed for a final class?

cc'ing Erik, who's working on stack promotion. We need to know the object's lifetime by proving it isn't escaped to somewhere that can extend its lifetime, which is hard to guarantee if you're calling functions from other modules. To guarantee a stack allocation it might be reasonable to have an attribute to say "I want this object to be stack allocated, so assert that it's still uniquely referenced by the time it goes out of scope" or something like that.

-Joe
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20151223/e8ca5f35/attachment.html>


More information about the swift-evolution mailing list