I wonder what is the best way to allocate and deallocate box2d objects (b2World and b2Body) in cocos2d for iOS?
using idiomatic, modern C++.
@property (nonatomic, assign) b2World * world;
@property (nonatomic, assign) b2Body * body;
No
(unless you implement these yourself properly, which requires much more understanding of the language)
-(void)dealloc {
delete _world;
_world = nil;
_body = nil;
No
details below.
Can somebody explain why I can not use retain and release for b2World and b2Body
these are C++ types, not objc types. C++ types may be allocated in many regions (e.g. on the stack, heap, or user defined areas) -- C++ types sre not reference counting aware. if reference counting is what you need, see std::shared_ptr
. std::shared_ptr
is rarely ever needed in C++, btw -- if you use several of these, you are likely doing something wrong.
and why do we use delete _world in dealloc method?
that's how C++ objects are destroyed and freed. specifically, single objects which were created using new
. and delete
and you should never have to write delete
or delete[]
-- use smart pointers if you have the unusual case where value is unsuitable.
Why do we not delete body objects also?
you would have to ask the programmer who wrote it -- it's either a leak, or referenced/owned elsewhere.
When setting pointers to nil: should I use nil or NULL?
0
Anyways, to get to your subject:
You would generally use this if the objects have default constructors:
@interface MONObject : NSObject {
@private
b2World world;
b2Body body;
}
@end
if you can place those in your @implementation
block, do so.
and your object would be default constructed before -init
(unless you set GCC_OBJC_CALL_CXX_CDTORS
to NO
, which is a very bad idea).
and your dealloc would look like this:
- (void)dealloc {
[super dealloc];
}
in this case, you would just not implement dealloc
. the destructors will be called (provided GCC_OBJC_CALL_CXX_CDTORS
is enabled).
when you want something more complex than a value (seen above), use a smart pointer.
finally, be careful how you pass and return C++ types -- they know how to copy themselves. so returning a value (for example) can actually perform very complex copying.