Mixing C++ and Objective-C
You can use smart pointer only on c++ classes. if you use then on objective-c classes you will either get compile error or crash somewhere.
You can also use containers with pointers of objective-c classes like
std::vector<CCSprite *> spriteList;
just make sure you retain them when you insert them to list and release them when you remove them.
In both cases, you can make a smart pointer of your own that calls retain and release in constructor/destruct/copy like needed and then don't worry about retain release.
Also destructor for member c++ objects will be called automatically when the object is deallocated.
An example of an objective c wrapper would be
template<typename T>struct shared_objc_object{ T *Object; shared_objc_object : Object(nil) { } shared_objc_object(T *Object) : Object([Object retain]) { } shared_objc_object(shared_objc_object &other) : Object([other.Object retain]) { } ~shared_objc_object() { [Object release]; } shared_objc_object &operator =(shared_objc_object &other) { [Object release]; Object = [other.Object retain]; }}
And you can use
std::vector<shared_objc_object<CCSprite *>> spriteList;spriteList.push_back(some_sprite);
and don't care about retain/release
There are some issues you'll want to be aware of. C++ classes do not enjoy the same scope based lifetime you might be used to when made into class members of Objective-C++ objects. When alloc
/init
ing, the constructor won't be called, and when releasing
, the destructor won't be called, unless you carefully use in place new
/delete
or hold on to a pointer and explicitly manage it with new
/delete
.
Also, if the Objective-C++ header needs to be shared with Objective-C files, you cannot use any C++ constructs at all. Both problems can be mitigated by hiding all C++ members using the pimpl pattern.
Can I mix STL containers with Objective-C or Cocos2D objects?
Yes, since Objective-C objects are just pointers to structs, you can store them easily in STL containers and even forward declare the type and pass it into pure C++ code. (Note, the C++ code can't really do much with the pointer without tricky and brittle code, but you can always pass the pointer back into Objective-C code later to get useful work done.)
Memory management using C++ smart pointer object in Objective-C?
You can use smart pointers to manage the lifetime of your Objective-C objects, but you will need to be careful that they do not call delete
(the default behavior for most C++ smart pointers). With shared_ptr from C++11 or boost, you can provide a custom deleter; though now you have two reference counting systems. You can instead use boost::intrusive_ptr to skip that extra overhead and use Objective-C's reference counting directly.