0

In Cocos2d-x 3.0 some vars are defined with * and some others are not. To me they are all pointers to instances of some Cocos classes, but I don't understand quite enough the difference. Examples:

Point myPoint;
Sprite* mySprite;

Also the way to construct both seem difference. And finally I also don't understand if my own classed should have * or not.

Tatanan
  • 207
  • 2
  • 10
  • 1
    you'll find an explanation here: http://stackoverflow.com/questions/1064325/why-not-use-pointers-for-everything-in-c/1064388#1064388 – CodeSmile May 08 '14 at 17:57
  • 1
    if you subclass a Cocos2d-x class that is a pointer your class needs to be a pointer too. – GameDeveloper May 08 '14 at 18:19
  • @LearnCocos2D According to this link, we should never use *, since it is slower and forces you to manage memory. So, why then many Cocos classes come with *? – Tatanan May 08 '14 at 18:43
  • 2
    Never say never. Slower is relative. In many cases you just *have* to create objects on the heap. It's also a matter of object lifetime, stack objects assigned to local variables will be released when the method returns. Many objects need to persist much longer however. And that should guide the decision. Both variants are common practice and while there is some overlap each serves a specific purpose. Ease of use & speed vs lifetime & object relation. – CodeSmile May 08 '14 at 20:28
  • @LearnCocos2D Then, I am understood properly, if I need an object to persist forever or long time, I should use *, but if I need temporary data or local data I shouldn't? Is it more or less this way? Examples: UserController* userController; or MyPlayer* myPlayer; should be with * since they are "important" persistent vars of my game, but MyPosition myPosition; BallEffect ballEffect should not have * since they specific local data of a method of Ball ball. Am I right? – Tatanan May 09 '14 at 07:46
  • 1
    Can't say without context, but seems about right though it really depends on each specific use case. Generally short-lived objects can reside on the stack, long-lived objects must be allocated on the heap with new. – CodeSmile May 09 '14 at 08:05
  • @LearnCocos2D Ok, I think I'm starting to understand. But, what happens if I have a stack pointer `Point point` (without *) but it is stored on an attibute of a long-lived object. Will it persist forever (as it is expected)? Example: `MySuperClass* m; MyData d; m->d = d;` In such case, will d live forever stored on m? – Tatanan May 09 '14 at 09:13
  • 1
    My C++ is rusty but I believe as long as m lives, d will live. I've certainly seen "stack" member variables before. Members can be allocated on the stack and will live along with the object because there's space reserved for them when the class object is allocated. – CodeSmile May 09 '14 at 11:45

0 Answers0