在 Objective-C++ 中存储 Obj-C 对象时,STL 容器是否支持 ARC?

Do STL containers support ARC when storing Obj-C objects in Objective-C++?

例如,这个会不会泄漏?

static std::tuple<CGSize, NSURL *> getThumbnailURL() {
  return std::make_tuple(CGSizeMake(100, 100), [NSURL URLWithString:@"http://examples.com/image.jpg"]);
}

不,它不会泄漏。该 NSURL 对象将由 ARC 正确管理。

http://clang.llvm.org/docs/AutomaticReferenceCounting.html#template-arguments

If a template argument for a template type parameter is an retainable object owner type that does not have an explicit ownership qualifier, it is adjusted to have __strong qualification.

std::tuple<CGSize, NSURL *> 等同于 std::tuple<CGSize, NSURL __strong *>。因此 NSURL 对象将在 std::tuple 实例被销毁时被释放。

是的,它们有效。 STL 容器是模板化的(STL = Standard Template Library),因此每当您使用一个容器时,就好像您用替换为(模板实例化)中的模板参数重新编译了它们的源代码。如果您用替换的模板参数重新编译它们的源代码,那么 ARC 将执行该代码中托管指针类型所需的所有适当的内存管理。

另一种思考方式是,ARC 托管指针类型实际上是 C++ 智能指针类型——它们有一个将其初始化为 nil 的构造函数,一个释放现有值并保留 (或对于块类型,复制)新值,以及释放该值的析构函数。因此,尽管 STL 容器与类似的 C++ 智能指针类型一起工作,但它们与 ARC 管理的指针类型一起工作。