• Announcements

    • khawk

      Download the Game Design and Indie Game Marketing Freebook   07/19/17

      GameDev.net and CRC Press have teamed up to bring a free ebook of content curated from top titles published by CRC Press. The freebook, Practices of Game Design & Indie Game Marketing, includes chapters from The Art of Game Design: A Book of Lenses, A Practical Guide to Indie Game Marketing, and An Architectural Approach to Level Design. The GameDev.net FreeBook is relevant to game designers, developers, and those interested in learning more about the challenges in game development. We know game development can be a tough discipline and business, so we picked several chapters from CRC Press titles that we thought would be of interest to you, the GameDev.net audience, in your journey to design, develop, and market your next game. The free ebook is available through CRC Press by clicking here. The Curated Books The Art of Game Design: A Book of Lenses, Second Edition, by Jesse Schell Presents 100+ sets of questions, or different lenses, for viewing a game’s design, encompassing diverse fields such as psychology, architecture, music, film, software engineering, theme park design, mathematics, anthropology, and more. Written by one of the world's top game designers, this book describes the deepest and most fundamental principles of game design, demonstrating how tactics used in board, card, and athletic games also work in video games. It provides practical instruction on creating world-class games that will be played again and again. View it here. A Practical Guide to Indie Game Marketing, by Joel Dreskin Marketing is an essential but too frequently overlooked or minimized component of the release plan for indie games. A Practical Guide to Indie Game Marketing provides you with the tools needed to build visibility and sell your indie games. With special focus on those developers with small budgets and limited staff and resources, this book is packed with tangible recommendations and techniques that you can put to use immediately. As a seasoned professional of the indie game arena, author Joel Dreskin gives you insight into practical, real-world experiences of marketing numerous successful games and also provides stories of the failures. View it here. An Architectural Approach to Level Design This is one of the first books to integrate architectural and spatial design theory with the field of level design. The book presents architectural techniques and theories for level designers to use in their own work. It connects architecture and level design in different ways that address the practical elements of how designers construct space and the experiential elements of how and why humans interact with this space. Throughout the text, readers learn skills for spatial layout, evoking emotion through gamespaces, and creating better levels through architectural theory. View it here. Learn more and download the ebook by clicking here. Did you know? GameDev.net and CRC Press also recently teamed up to bring GDNet+ Members up to a 20% discount on all CRC Press books. Learn more about this and other benefits here.
Sign in to follow this  
Followers 0
ASnogarD

Using New and Delete in inherited classes and stored pointers to the new object

11 posts in this topic

I am using much of the framework I got from [url="http://www.sdltutorials.com/"]http://www.sdltutorials.com/[/url] , and while its entity class is great for creating new player entities I cant get the thing to make bullet entities... least not without generating exception faults.

The way to make a player entity is straight forward, declare it in the source file , load its assets when entering the in game state and clear the assets when exiting ... no problem.

The bullets however pose a number of issues, I cant declare each bullet beforehand.... they need to be created dynamically so I create one each time the player fires, and store it in the entity vector like the player... and when the bullet collides with a wall it dies, so I delete it and erase the element in the vector it was stored in.

Code to create a bullet :

[CODE]
Entity_Bullet* pBullet = new Entity_Bullet;
pBullet->OnLoad(16,16,1,ENTITY_TYPE_BULLET_PLAYER);


if(Facing == ENT_DIR_RIGHT)
{
pBullet->MoveRight = true;
pBullet->MoveLeft = false;

pBullet->X = X + Width;
pBullet->Y = Y + (Height/2);
}
if(Facing == ENT_DIR_LEFT)
{
pBullet->MoveLeft = true;
pBullet->MoveRight = false;
pBullet->X = X - 20;
pBullet->Y = Y + (Height/2);
}

Entity::EntityList.push_back(pBullet);

[/CODE]

The entity list is declared like this : std::vector<Entity*> Entity::EntityList;
The code to remove the bullet is in the ingame state loop, where it goes through the entity vector and calls up each element.

[CODE]
// Move , Animate and calculate actions for ALL entities
for(unsigned int i = 0; i < Entity::EntityList.size(); i++)
{
if(!Entity::EntityList[i]) continue;

Entity::EntityList[i]->OnLoop();

// If the entity is not a player
if(Entity::EntityList[i]->Type != ENTITY_TYPE_PLAYER)
{
// If the Entity is suppose to be destroyed
if(Entity::EntityList[i]->Dead == true)
{
Text::AddText("Dead one here", 10, 400);
Entity::EntityList[i]->OnCleanup();
if(Entity::EntityList[i]->Type == ENTITY_TYPE_BULLET_PLAYER)
{
delete Entity::EntityList[i];
}

Entity::EntityList.erase(Entity::EntityList.begin() + (i --));
}
}

}
[/CODE]

The issue seems to be in the clearing up portion, I think there is a conflict in the vector when a few bullets are made and destroyed... I am thinking it is trying to store a bullet in a vector that was deleted but not cleared ?
If I remove the delete and erase portions of the entity loop it runs without crashing, just leaves bullets all over the place.

I would prefer the actual bullet class to delete the bullet during the OnCleanup() call, but using delete this crashes the game as soon as a bullet is fired, and I cant think of a way to identify the particular bullet beyond a this call.

Hmm, would the bullet object go out of scope if the pointer ( or rather the element the pointer was erased ? ).

Tips , ideas , advice welcome ... thanks.



[i]FYI - I havent just copied the tutorials code , I have modified a number of things in the code except for portions where I like how it works, ie I havent just copy pasted someone elses code and want you to sort out the bugs.[/i] Edited by ASnogarD
0

Share this post


Link to post
Share on other sites
Update:

As a test I disabled :

if(Entity::EntityList[i]->Type == ENTITY_TYPE_BULLET_PLAYER)
{
delete Entity::EntityList[i];
}
Entity::EntityList.erase(Entity::EntityList.begin() + (i --));

I re-enabled : Entity::EntityList.erase(Entity::EntityList.begin() + (i --)); to clear the element and it clears out the bullets from the game... but I cant tell if it actually removes the bullets from memory as well.... or am I just removing the pointers to the objects from the vector but not getting rid of the actual objects ?

It doesnt crash the game, and the bullets are not left of the screen... just wonder if the bullet objects are still in memory ?
0

Share this post


Link to post
Share on other sites
If you created an object with new and didn't call delete on it, then the object will be there. Just getting rid of all pointers to the objects will not get rid of the objects themselves - if you are using normal pointers. If you use [url=http://en.wikipedia.org/wiki/Smart_pointer]smart pointers[/url] then they will automatically get rid of objects when the last smart pointer referencing the object goes away. If you possess a relatively up to date C++ compiler you can use std::shared_ptr. If not, look into using boost::shared_ptr.
1

Share this post


Link to post
Share on other sites
Thanks for the reply, I will look into smart pointers at some time.

I got the code to delete the objects successfully with delete this , the crash seems to be caused by too many events when I press the fire button too quickly... I guess there is a problem when you pass an event too much.
Do you think passing SDL_Event objects through a number of functions could cause issues ?
Currently an event gets passed from the main loop, to the statemanager, to the ingame state, to the player object... if I press the fire button.

*sigh* coding is such a pain when it goes wrong [img]http://public.gamedev.net//public/style_emoticons/default/tongue.png[/img]

I give for now... to test if it was me mashing the fire button to get lots of bullets out.... I disabled the actual bullet create portion of the code...so each time I fired it merely reported to my ingame console bullet fired... and didnt crash at all.
So the issue is still with the entities. Edited by ASnogarD
0

Share this post


Link to post
Share on other sites
[quote name='ASnogarD' timestamp='1345557864' post='4971827']
I got the code to delete the objects successfully with [b][color=#ff0000]delete this[/color][/b] , <snipped>
[/quote]

do you actually have something like that in your code:
[source lang="cpp"]void SomeClass::someMethod()
{
delete this;
}[/source]

When using construct like that, there are certain precaution you may need to be aware.
0

Share this post


Link to post
Share on other sites
In brief the delete this was in a cleanup() called via a pointer to the base class of the bullets , the pointer is stored in a vector of pointers of entity object types and there is a loop that basically calls the cleanup like :

Entity::EntityList[i]->OnCleanup();

It was working, I had a static counter counting each time the constructor made a object and it took one off each time the destructor was called... the destructor was called each time the OnCleanup() was called to delete this on the bullets ( ie the destructor was called each time the bullet got deleted - confirmed because I had the destructor report each time it was called).

Its moot now as the code crashed out in the loop when firing, it would sometimes work for a bit then crash or crash as soon as I shoot the first bullet... it was unstable as hell.
I basically deleted all the entity, player and collision classes and going to rewrite it in my own way instead of trying to adapt the tutorials entity system (its wierd the tutorial seemed to offer so much flexibility and elegant solutions to dealing with lots of entities... but on closer inspection, it seemed limited to only making 1 or 2 player entities ).


edit: ym seplilign scuks. Edited by ASnogarD
0

Share this post


Link to post
Share on other sites
If I understand correctly, the Entity was deleted by using [color=#ff0000][b]delete this[/b][/color] inside OnCleanup() method, but have you removed that pointer from the list Entity::EntityList? If you did not, then you have what is called dangling pointer. It underscores what SiCrane was saying about using smart pointer to manage memory and life time of objects.

[url="http://en.wikipedia.org/wiki/Dangling_pointer"]http://en.wikipedia....angling_pointer[/url]
1

Share this post


Link to post
Share on other sites
The element in the vector that held the pointer is erased after the OnCleanup() call, using :

Entity::EntityList.erase(Entity::EntityList.begin() + (i --));

I was under the impression that erasing the element holding the pointer would remove the pointer from the system ?

What really makes it confusing is the crash is pointing to the part of the code that control the game states ( ie menu or in game, or in the editor )... and that is pretty basic, I cant see how creating and deleting entities in the ingame state would crash the state manager... and when I remove the statemanager and all the states so the game is called directly by the main loop ...it crashes there, but not in the for loop that runs through the EntityList vector.

I am re-writing the player entity code, same stuff but checking each line more carefully ( had re-wrote the whole lot a few times and got lazy in some sections ).
0

Share this post


Link to post
Share on other sites
[source lang="cpp"]Entity::EntityList[i]->OnCleanup();
if(Entity::EntityList[i]->Type == ENTITY_TYPE_BULLET_PLAYER)
{
delete Entity::EntityList[i];
}
[/source]

Just to clarify here.
when you call OnCleanup() method, you said that you are doing this in it: [color=#b22222][b]delete this[/b][/color]. This will delete that instance of an object which in your case is object at Entity::EntityList[i], but after that you are trying to access member variable with this line:
[source lang="cpp"]Entity::EntityList[i]->Type[/source]
and then you end-up deleting that object
[source lang="cpp"]delete Entity::EntityList[i];[/source]
which was already deleted by using delete this, hence you will get undefined behavior here.

If you goggle delete this you will find allot of resources and explanations. Here is a first one to get you started: [url="http://www.parashift.com/c++-faq/delete-this.html"]http://www.parashift...elete-this.html[/url] Edited by DoctorGlow
1

Share this post


Link to post
Share on other sites
That may of been a cause for sure, however I deleted those classes to re-write them so I cant go check now... however I am pretty certain I resorted to a delete this in the cleanup after the delete Entity::EntityList[i] seemed to cause crashes, but as I tried a number of things in a rush I cant remember for certain.

I will ensure that it doesnt do both in the new re-write I am busy with, thanks for the help... I do appreciate the effort, and the links .
0

Share this post


Link to post
Share on other sites
[quote name='ASnogarD' timestamp='1345676694' post='4972413']
That may of been a cause for sure, however I deleted those classes to re-write them so I cant go check now.[/quote]

Just FYI, it helps to use source control, even if you are the only one on the project, since then you will have all the history for all files and can go to any past version [url="http://en.wikipedia.org/wiki/Revision_control"]http://en.wikipedia....evision_control[/url].

As far as which one to use, I think FAQ here might have more info.
0

Share this post


Link to post
Share on other sites
Well I am happy to report that the problem is sorted... as best as I can tell I am clearing every bullet and the element in the entity store that was holding the pointer to the bullet.
I have a static counter counting bullets as the constructor is called, and taking one off each time the destructor is called... and the numbers are consistant, I also check the number of elements in my vector ( basic int variable counts 1 each time an element is called , reports total count after loop, then resets ) and it show 1 for the player and the number of bullets consistantly.

.... plus the FPS dips when there is a LOT of bullets fired (over 98 in one trial, with keyboard repeat enabled ) but returns to the usual values when the bullets are cleared... I assume if there is a lot of bullets lost in the system it would degrade performance.

I basically got the same code in but the approach was different. I basically wrote the player and bullet as thier own classes without inheriting the entity class , then got both to behave properly as seperate classes... then I created the entity class and got the player and bullet classes to inherit from it and set everything to work via polymorphic inheritance.
In short I got the 2 classes to work properly before I made them into a fancy inherited polymorphic tree to eliminate inheritance issues and polymorphism bugs.

Finally... now I can add enemy entities, finish off the level editor ...and a ton of other shite... why do I do this again for ? :P
0

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now
Sign in to follow this  
Followers 0