Welcome, Guest. Please login or register. Did you miss your activation email?

Author Topic: How to remove class/sprite  (Read 7422 times)

0 Members and 1 Guest are viewing this topic.

Nexus

  • SFML Team
  • Hero Member
  • *****
  • Posts: 6286
  • Thor Developer
    • View Profile
    • Bromeon
How to remove class/sprite
« Reply #15 on: December 09, 2010, 11:28:11 pm »
Quote from: "prchakal"
So nexus, what you recommend?
I have already given you some improvement suggestions, so I don't know what you mean.

Quote from: "prchakal"
To delete the class from memory, i invoke:
Code: [Select]
delete this;And now the destructor is called.
I wouldn't do that. In the very most cases, the instance which is in charge of allocating the object should also deallocate it for symmetry reasons. With your approach, you enforce the use of the new operator and therefore manual memory management (which should be avoided wherever possible). One can neither lay an Enemy on the stack, nor create a temporary object of it, nor put it inside a smart-pointer.

If I were you, I would either use Boost's pointer containers (the probably best approach), or delete each element before it is erased. If you have the TR1, std::tr1::shared_ptr might be an alternative.
Zloxx II: action platformer
Thor Library: particle systems, animations, dot products, ...
SFML Game Development:

prchakal

  • Full Member
  • ***
  • Posts: 142
    • View Profile
How to remove class/sprite
« Reply #16 on: December 10, 2010, 02:54:44 pm »
Hi,

With boost smartpointer, when i do the ERASE from vector it will be deleted?

Do you have a function example?

Nexus

  • SFML Team
  • Hero Member
  • *****
  • Posts: 6286
  • Thor Developer
    • View Profile
    • Bromeon
How to remove class/sprite
« Reply #17 on: December 11, 2010, 01:05:45 pm »
Quote from: "prchakal"
With boost smartpointer, when i do the ERASE from vector it will be deleted?
Yes. As soon as the smart-pointer object is destroyed, the memory is deallocated. But if you are already using Boost, you should try the pointer-containers. They are much more specialized and optimized for this purpose.

Anyway, I wonder why you need pointers. Do you need polymorphism, or are your Enemy instances noncopyable or unique? If not, the straightforward approach is to store Enemy objects using STL containers:
Code: [Select]
std::vector<Enemy> v;
v.push_back( Enemy(...) );
v[0].Attack();
v.erase(v.begin());             // Memory is freed

Then the Boost pointer-container approach, storing Enemy* pointers:
Code: [Select]
boost::ptr_vector<Enemy> v;
v.push_back( new Enemy(...) );  // Insert pointer to object
v[0].Attack();                  // No additional dereferencing (no ->, just .)
v.erase(v.begin());             // Memory is freed
Zloxx II: action platformer
Thor Library: particle systems, animations, dot products, ...
SFML Game Development:

 

anything