Is it acceptable to call a destructor?

Started by
39 comments, last by yckx 11 years, 6 months ago
Ofc you can use it that way. It will looks smth like this:
We run loop on an array of some objects to check some abstract requirement.
[source]#include <stdio.h>
#include <list>
class A {
public:
A() {
printf("A:constructor.\n");
}
~A() {
printf("A:destructor.\n");
}
};
int main() {
std::list<A*> objects;
printf("Allocate 10 objects of A\n");
for (int i = 0; i < 10; i++)
objects.push_back(new A());

printf("Time to die\n");
int list_size = objects.size();
for (int i = 0; i < list_size; i++) {
A* deadbeef = *(objects.begin());
objects.erase(objects.begin());
delete deadbeef;
}
printf("Elements in list: %d\n", objects.size());
}
[/source]
Output:

Allocate 10 objects of A
A:constructor.
A:constructor.
A:constructor.
A:constructor.
A:constructor.
A:constructor.
A:constructor.
A:constructor.
A:constructor.
A:constructor.
Time to die
A:destructor.
A:destructor.
A:destructor.
A:destructor.
A:destructor.
A:destructor.
A:destructor.
A:destructor.
A:destructor.
A:destructor.
Elements in list: 0


But this is now clever 'cause memory allocation is kinda slow operation. Much better if we will save memory for such type of object and use it letter.

[source]
#include <stdio.h>
#include <list>
class A {
public:
A() {
printf("A:constructor.\n");
}
~A() {
printf("A:destructor.\n");
}
void Clear() {
}
};
class AAlloc {
std::list<A*> _cache;
public:
A* Alloc() {
if (!_cache.empty()) {
A* deadbeef = _cache.front();
_cache.erase(_cache.begin());
deadbeef->Clear();
return deadbeef;
}
return new A();
}
void Dealloc(A* obj) {
_cache.push_back(obj);
}
~AAlloc() {
std::list<A*>::iterator itr = _cache.begin();
for ( ; itr != _cache.end(); ++itr) {
delete *itr;
}
}
};
int main() {
std::list<A*> objects;
AAlloc allocator;
printf("Allocate 10 objects of A\n");
for (int i = 0; i < 10; i++)
objects.push_back(allocator.Alloc());

printf("Time to die\n");
{
std::list<A*>::iterator itr = objects.begin();
for ( ; itr != objects.end(); ++itr) {
allocator.Dealloc(*itr);
}
objects.clear();
}
printf("One more allocation of 10 objects\n");
for (int i = 0; i < 10; i++)
objects.push_back(allocator.Alloc());
printf("IT\'S A GOOD DAY TO DIE!\n");
{
std::list<A*>::iterator itr = objects.begin();
for ( ; itr != objects.end(); ++itr) {
allocator.Dealloc(*itr);
}
objects.clear();
}
printf("Elements in list: %d\n", objects.size());
}
[/source]

New output:

Allocate 10 objects of A
A:constructor.
A:constructor.
A:constructor.
A:constructor.
A:constructor.
A:constructor.
A:constructor.
A:constructor.
A:constructor.
A:constructor.
Time to die
One more allocation of 10 objects
IT IS A GOOD DAY TO DIE!
Elements in list: 0
A:destructor.
A:destructor.
A:destructor.
A:destructor.
A:destructor.
A:destructor.
A:destructor.
A:destructor.
A:destructor.
A:destructor.


It's maybe looks pretty tricky but the main reason is speed up application.
C x 2 C x o C x C f nice C x C s C x C c
Advertisement
It's probably preferable in this case to do some kind of mark-and-sweep pattern (As Brother Bob showed). Its possible to call a destructor safely, but only in very specific circumstances.

throw table_exception("(? ???)? ? ???");


[quote name='alvaro' timestamp='1350588033' post='4991525']
[Waits for someone to post some std::remove_if invocation in response to BeerNutts's code...]

That was my first reaction as well:
[source]
EnemyList.erase(
std::remove_if(
std::begin(EnemyList),
std::end(EnemyList),
[](Enemy &e) {return e.Update() == ENEMY_DEAD;}),
std::end(EnemyList));
[/source]
[/quote]

IMO, this kind of code shouldn't be introduced in a "For Beginner's" forum. It's likely to add confusion rather than help. I try to keep things simple when replying here.

My Gamedev Journal: 2D Game Making, the Easy Way

---(Old Blog, still has good info): 2dGameMaking
-----
"No one ever posts on that message board; it's too crowded." - Yoga Berra (sorta)

Not trying to hijack the thread here but placement new isn't useless or "almost never used". Lots of large games need their own memory manager with a smart point/reference system and want their objects to be allocated in their memory management system's contiguous, managed heap. Thus placement new operator is used to put them there rather than in statically allocated bits of memory. I've done this before myself.

But I agree that use of placement new is not common; it's simply not necessary most of the time. But in large, AAA games that can be dealing with several GB of memory it's often a good idea to have a memory manager and use placement new.
_______________________________________________________________________________
CEO & Lead Developer at ATCWARE™
"Project X-1"; a 100% managed, platform-agnostic game & simulation engine

Please visit our new forums and help us test them and break the ice!
___________________________________________________________________________________

[quote name='Brother Bob' timestamp='1350589406' post='4991534']
[quote name='alvaro' timestamp='1350588033' post='4991525']
[Waits for someone to post some std::remove_if invocation in response to BeerNutts's code...]

That was my first reaction as well:
[source]
EnemyList.erase(
std::remove_if(
std::begin(EnemyList),
std::end(EnemyList),
[](Enemy &e) {return e.Update() == ENEMY_DEAD;}),
std::end(EnemyList));
[/source]
[/quote]

IMO, this kind of code shouldn't be introduced in a "For Beginner's" forum. It's likely to add confusion rather than help. I try to keep things simple when replying here.
[/quote]
And in my opinion, a loop with strange loop increment conditions and logic is not better that code that has well defined parameters and function calls. I can separate the remove and the erase calls into separate statements if you want to simplify and understand the logic behind it, something that's going to be very difficult with your loop since the two are tightly coupled with each other.

Removed some namespace qualifiers as well if you want to clean up the code a bit.
[source]
auto pred = [](Enemy &e) {return e.Update() == ENEMY_DEAD;};
auto last = remove_if(begin(EnemyList), end(EnemyList), pred);

EnemyList.erase(last, end(EnemyList));
[/source]

It's a matter of taste and what you already know and what you want to learn. Your code may be simpler for you but my code is certainly simpler for me. Both codes have their details you have to know about to understand them. For example, your code requires knowledge about how iterators work when removing elements from a container you iterate over, while my code requires knowledge of function objects of some kind (lambda expressions in my particular example, but you can use functors or just plain function pointers as well). On that topic, I can argue that, in general, knowing major things such as lambda expressions and standard library functions is more important that knowing mostly irrelevant details such as how to adjust a iterator once you have removed an element from a container. I call it irrelevant since it mostly occurs in situations where the standard library already has a function for it.

Just saying that "easy" is in the eye of the beholder.

[source]
auto pred = [](Enemy &e) {return e.Update() == ENEMY_DEAD;};
auto last = remove_if(begin(EnemyList), end(EnemyList), pred);

EnemyList.erase(last, end(EnemyList));
[/source]

Too many C++0x. I guess it's difficult for novices. Don't you think so?

But however your code show me some interesting points. Thanks
C x 2 C x o C x C f nice C x C s C x C c

[quote name='Brother Bob' timestamp='1350599800' post='4991582']
[source]
auto pred = [](Enemy &e) {return e.Update() == ENEMY_DEAD;};
auto last = remove_if(begin(EnemyList), end(EnemyList), pred);

EnemyList.erase(last, end(EnemyList));
[/source]

Too many C++0x. I guess it's difficult for novices. Don't you think so?

But however your code show me some interesting points. Thanks
[/quote]
Both yes and no.

Yes, the whole solution is too much to digest for a beginner. For a beginner of programming that is, but not necessary for a beginner of C++ that has some basic experience with other languages.

No, I don't think the C++11 parts of my solution makes it difficult. Very much the opposite in fact. Consider the variable declarations that would be necessary for pred and last if it wasn't for the auto keyword. Consider the beauty of specifying code directly where it is used instead of somewhere else.

With reservation for some syntax errors of course, even VS2010 with it's very limited C++11 support can compile it. There's really nothing exceptional and brand new about it.
Yeah, I have used a similar procedure for collisions and deallocation before. Something like the following:


// at some point in code
projectile missile;
new enemy[num];

// check for enemy collisions
for (short i = 0; i < num; i++)
{
enemy.move();

if (enemy.collide(missile) == true)
delete enemy;
}



Please note that this is highly abridged. My game's world is actually based around a character array, so I don't even have to pass the object, just a character value.

Thanks for all your help though; I understood when BeerNutts mentioned the increment step being messed up because of calling the destructor.

How do you ensure that the destructor isn't called again when the object is actually about to be destroyed (for example goes out of scope, you release the memory by calling delete, or removing the object from an std::vector)?

What's wrong with having the outside logic taking care of that? If the enemy destroys itself, then that kind of implies that the enemy itself is responsible to handling the collision with projectiles. Isn't that a job for some outside component to handle collisions, like a physics component or something?

Exactly what Brother Bob says; why would you allow an object to self destruct? If the enemy class had a bool collision(vec3 from_pt, vec3 to_pt) and returned true
for collision, you could handle destruction just after handling the bullet physics.
To separate your subsystems collision, game logic, models etc, you'd probably want to go with those bloody iterations, flags and internal messaging systems anyways,
but it's "nicer" to delete or std::pop() / remove than it is to selfdestruct. IMO.

EDIT: Oh, I just noticed that you've taken it a few steps further. I will leave you two to it. :)
Are you saying I put it a step further, lol?

I'm unfamiliar with the syntaxes some of you are giving me, or I don't really find them very clean/readable (no offense). So to me it looks like I'm doing less work or I'm lacking in some area of efficiency or functionality. I kind of think that way whenever I run into an unfamiliar syntax or code that looks intimidating to read through.

Compared to the methods that have been discussed in the thread compared to my posted way of doing it, which is the best in terms of efficiency and cleanliness? In C++ or something similar, please. Or even pseudocode!

This topic is closed to new replies.

Advertisement