[swift-evolution] Evolving UnsafeMutablePointer.alloc (was Re: [Review] SE-0006 Apply API Guidelines to the Standard Library)

Dave Abrahams dabrahams at apple.com
Sun Jan 24 16:27:38 CST 2016


on Sat Jan 23 2016, Joe Groff <swift-evolution at swift.org> wrote:

>> On Jan 22, 2016, at 11:31 PM, Guillaume Lessard via swift-evolution <swift-evolution at swift.org> wrote:
>> 
>> Hello,
>> 
>> I disagree with the following change to UnsafeMutablePointer:
>
>> -  public static func alloc(num: Int) -> UnsafeMutablePointer<Pointee>
>> +  public init(allocatingCapacity count: Int)
>> 
>> This would make it the only constructor in any of OpaquePointer,
>> UnsafePointer, UnsafeMutablePointer and UnsafeReference to have the
>> side-effect of allocating memory. All the others are relatively
>> cheap transformations on pointer values, and get used a lot for
>> typecasting. An allocating constructor would be less locatable among
>> such uses of typecasting-via-constructor. The memory-allocating
>> static method has the merit of sticking out, and pairs nicely with
>> the necessary deallocation call, like the malloc/free pair.
>
> This all probably deserves a separate discussion from the overall
> umbrella proposal. Another thing to consider here is whether the logic
> to allocate an array of values really belongs on
> UnsafeMutablePointer—it seems like a better fit for
> UnsafeMutableBufferPointer, whose whole job is to reference an array
> of objects in memory. 
>
> Currently, you need to allocate the memory using
> UnsafeMutablePointer.alloc, then immediately wrap it in a
> BufferPointer with the same count, which is a bit awkward.

You make a good point, Joe.  Why would we throw out the size
information immediately after allocating the memory?

*On the other hand*, UnsafeMutableBufferPointer is really not designed
to support allocated-but-initialized memory, and I think I'd prefer to
keep it that way.  I don't think once you step into unsafe-land, you
should have to live more dangerously than the individual situation
requires, and modifying part of an array without ARC overhead is an
important use-case.

For buffers with some uninitialized elements we have ManagedBuffer et
al., but of course that doesn't cover the use-case of manual memory
deallocation.  So maybe a different component altogether—or some kind of
more-general unification of these components—is what we need in the long
run.  Definitely more appropriate to pursue this in another thread.

>
> -Joe
> _______________________________________________
> swift-evolution mailing list
> swift-evolution at swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution

-- 
-Dave



More information about the swift-evolution mailing list