swift 3 中是否有等效的 c++ shared_ptr?

Is there an equivalent of c++ shared_ptr in swift 3?

本文关键字:shared c++ ptr 是否 swift      更新时间:2023-10-16

我知道 swift 3 中的强(默认)和弱(带有弱关键字)引用,但是否有等效的共享引用?

谢谢

Swift 中的内存管理范式与 C++ 不同,因为它继承了 Objective-C 的保留释放机制(通过 ARC)。正如您所料,C++的解决方案减少了编译器的责任,更具表现力和优化性,但使用起来也更复杂。

所以,回答你的问题:strong(默认)基本上像shared_ptr一样工作,weak就像weak_ptrunique_ptr没有直接的等价物。但是,如果编译器能够保证指针的唯一性,一些强变量可能会像unique_ptr一样(例如,您在同一范围内创建和销毁对象 - 如函数的主体 - 而不将其分配给任何变量)

当然,这仅适用于引用类型。值类型只是复制的。

Swift 应用强引用的 ARC(自动引用计数)来决定何时释放引用类型实例使用的内存(即,当对该对象的引用数为零时)。ARC 及其引用计数自动运行,但与显式使用C++的std::shared_ptr相似;后者将允许指向的对象(通过共享 PTRS)被销毁(例如,由提供的删除器),前提是指向该对象的所有智能指针都超出范围或被显式重置(/nulled)。

在上面的例子中,你可以将强不可变(引用)foobar(后者从foobar()返回)视为std::smart_ptr的C++的等价物:它们都指向同一个Foo对象,只有当两者都超出范围时,才会取消初始化对象。

class Foo {
init() { print("initializing") }
deinit { print("deinitialized") }
}
func foobar() -> Foo {
let foo = Foo() // strong reference
let bar = foo   // another strong reference 
// total "shared" count is now 2
return bar
// reference associateced with 'foo' goes 
// out of scope, but the reference associateced
// with 'bar' is returned from the function, and
// thus, ARC still keeps the Foo instance alive.
}
func bar() {
print("calling foobar ...")
let bar = foobar() // retains the reference from 'bar' in foobar()
print("foo() is now out of scope")
print("leaving bar() scope ...")
} // 'bar' of bar() goes out of scope: Foo object should be deinitialized
bar()
/* calling foobar ...
initializing
foo() is now out of scope
leaving bar() scope ...
deinitialized             */
/* ^^^^^^^^^^^^^- ok */

普通变量(没有弱或无主修饰符)与shared_ptr具有类似的语义。