swift 3 中是否有等效的 c++ shared_ptr?
Is there an equivalent of c++ shared_ptr in swift 3?
我知道 swift 3 中的强(默认)和弱(带有弱关键字)引用,但是否有等效的共享引用?
谢谢
Swift 中的内存管理范式与 C++ 不同,因为它继承了 Objective-C 的保留释放机制(通过 ARC)。正如您所料,C++的解决方案减少了编译器的责任,更具表现力和优化性,但使用起来也更复杂。
所以,回答你的问题:strong
(默认)基本上像shared_ptr
一样工作,weak
就像weak_ptr
,unique_ptr
没有直接的等价物。但是,如果编译器能够保证指针的唯一性,一些强变量可能会像unique_ptr
一样(例如,您在同一范围内创建和销毁对象 - 如函数的主体 - 而不将其分配给任何变量)
当然,这仅适用于引用类型。值类型只是复制的。
Swift 应用强引用的 ARC(自动引用计数)来决定何时释放引用类型实例使用的内存(即,当对该对象的强引用数为零时)。ARC 及其引用计数自动运行,但与显式使用C++的std::shared_ptr
相似;后者将允许指向的对象(通过共享 PTRS)被销毁(例如,由提供的删除器),前提是指向该对象的所有智能指针都超出范围或被显式重置(/nulled)。
在上面的例子中,你可以将强不可变(引用)foo
和bar
(后者从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具有类似的语义。
相关文章:
- 引用 std::shared:ptr 以避免引用计数
- dopen():不以 root 身份运行时"failed to map segment from shared object"
- 无法使用 libtool 将 -shared 参数传递给 g++
- 链接 boost 库时"Error while loading shared libraries"引发的,除了我无法使用 root 访问权限来修复它
- 解决方法:'can not be used when making a shared object; recompile with -fPIC'使用Cmake。使用普通的 g++ 工作
- gcc -fPIC vs. -shared
- 在shared_from_this()中的错误类型(在继承类中)(是否有dyn.type-ware shared Poi
- "directory containing symbolic versions of my app's shared libraries"的位置(ndk-stack)
- Qt自定义插件无法加载 - "Shared Library Not Found"
- C - Shared Library - dlopen, dlsym
- ubuntu 12.04 中的 openCV 程序编译错误"libopencv_core.so.2.4: cannot open shared object file: No such file or
- boost::shared_ptr和std::shared-ptr的同居
- 将GoogleMock与Boost::Shared Pointers一起使用时泄漏的Mock对象
- Singleton: C++ shared dll
- 传递"shared"指针的 OpenMP 任务
- CMake项目编译精细的SHARED库,但不使用STATIC库
- OpenCV: "libopencv_core.so.2.3: cannot open shared object file: No such file or directory"
- 我可以用std::shared_ptr而不是boost::shared-ptr构建boost库吗
- Qt5/c++ 在调试期间生成'Corrupted shared library list'错误
- 链接错误:"relocation R_X86_64_32 ... can not be used when making a shared object; recompile with -fPIC"