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

669 views Asked by At

For example, would this leak?

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

There are 2 answers

1
Kazuki Sakamoto On BEST ANSWER

No, it wouldn't leak. That NSURL object would be managed by ARC properly.

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 *> is the same as std::tuple<CGSize, NSURL __strong *>. Thus NSURL object will be released when the std::tuple instance is destructed.

0
newacct On

Yes, they work. STL containers are templated (STL = Standard Template Library), so whenever you use one it's as if you re-compiled their source code with the template arguments substituted in (template instantiation). And if you re-compiled their source code with the template arguments substituted in, then ARC would perform all the appropriate memory management necessary for the managed pointer types in that code.

Another way to think about it is that ARC managed pointer types are actually C++ smart pointer types -- they have a constructor that initializes it to nil, an assignment operator that releases the existing value and retains (or for block types, copies) the new value, and a destructor that releases the value. So as much as STL containers work with similar C++ smart pointer types, they work with ARC managed pointer types.