How to properly distribute and release box2d objects in cocos2d, iOS

I wonder what is the best way to allocate and free box2d objects (b2World and b2Body) in cocos2d for iOS?

Allocate

@property (nonatomic, assign) b2World * world; @property (nonatomic, assign) b2Body * body; 

Frees up

 -(void)dealloc { delete _world; _world = nil; _body = nil; 

Can someone explain why I cannot use save and release for b2World and b2Body and why we use delete _world in the dealloc method? Why don't we also remove body objects? (delete _body does not work). When setting pointers to zero: should I use nil or NULL?

+6
source share
1 answer

I wonder what is the best way to allocate and free box2d objects (b2World and b2Body) in cocos2d for iOS?

using idiomatic, modern C ++.


 @property (nonatomic, assign) b2World * world; @property (nonatomic, assign) b2Body * body; 

Not

(if you do not implement them yourself, which requires a much greater understanding of the language)


 -(void)dealloc { delete _world; _world = nil; _body = nil; 

Not

below.


Can someone explain why I cannot use save and release for b2World and b2Body

these are C ++ types, not objc types. C ++ types can be allocated in many regions (for example, on the stack, heap, or in user-defined areas). C ++ types sre not reference counting aware. if link counting is what you need, see std::shared_ptr . std::shared_ptr rarely required in C ++, btw - if you use several of them, you are probably doing something wrong.

and why do we use delete _world in the dealloc method?

that C ++ objects are destroyed and freed. in particular, individual objects created with new . and delete , and you will never have to write delete or delete[] - use smart pointers if you have an unusual case when the value does not fit.

Why don't we also remove body objects?

you would need to ask the programmer who wrote it is either a leak or a link / belonging somewhere else.

When setting pointers to zero: should I use nil or NULL?

0


In any case, to jump to the topic:

You usually use this if objects have default constructors:

 @interface MONObject : NSObject { @private b2World world; b2Body body; } @end 

if you can post them in your @implementation block do it.

and your object will default to -init (unless you set GCC_OBJC_CALL_CXX_CDTORS to NO , which is a very bad idea).

and your dealloc will look like this:

 - (void)dealloc { [super dealloc]; } 

in this case, you would not have implemented dealloc . destructors will be called (if GCC_OBJC_CALL_CXX_CDTORS is GCC_OBJC_CALL_CXX_CDTORS ).

if you need something more complex than the value (see above), use a smart pointer .

finally, be careful how you go through and return C ++ types - they can copy themselves. therefore, returning a value (for example) can actually do very complex copying.

+2
source

Source: https://habr.com/ru/post/922812/


All Articles