• 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
simpler

Destructor vs Cleanup()

29 posts in this topic

Hey I have bumped into a lot of code that uses a Cleanup() member function for their classes instead of using the destructor. I have found myself starting to mix both alternatives which feels bad and I'd rather want to be consistent. What are the pros and cons? What's your opinion?

EDIT: The same question goes for the constructor and Init(). Edited by simpler
1

Share this post


Link to post
Share on other sites
[quote name='frob' timestamp='1350053843' post='4989484']
It also makes sense for reusable objects, especially heavyweight objects that are expensive to create and destroy, but cheap to recycle.[/quote]
Let me rephrase my earlier statement to read: "One should never [b]aim[/b] to design code that requires a cleanup function in C++".

If you have an object which should be reused, or which lifetime should exceed its use, then consider allowing it to provide an RAII-compliant 'handle' object, which encapsulates the short-term operation.

[quote]An example of reusable objects would be the C++ file streams. You can use it once by create, open, close, then destroy; or reuse with create, open, close, open, close, open, close, ... etc., then destroy.[/quote]
Are fstreams really that heavyweight? Glancing at my local header files it looks like a mutex, a buffer, an underlying stream, and a handful of state variables. It seems to me that the cost of actually locking the mutex, and invoking an open syscall should dominate the construction costs of allocating the buffer.
0

Share this post


Link to post
Share on other sites
[quote name='swiftcoder' timestamp='1350061153' post='4989514']
[quote]An example [b]of reusable objects[/b] would be the C++ file streams. You can use it once by create, open, close, then destroy; or reuse with create, open, close, open, close, open, close, ... etc., then destroy.[/quote]
Are fstreams really that heavyweight? Glancing at my local header files it looks like a mutex, a buffer, an underlying stream, and a handful of state variables. It seems to me that the cost of actually locking the mutex, and invoking an open syscall should dominate the construction costs of allocating the buffer.
[/quote]Please reread my post. No, they are not heavyweight. They are reusable.
0

Share this post


Link to post
Share on other sites
[quote name='frob' timestamp='1350061504' post='4989518']
Please reread my post. No, they are not heavyweight. They are reusable.
[/quote]
Sure, they're reusable, but the heavy cost is in the open operation, not the object creation operation (except when the object creation includes the open operation).

Reusing an fstream is like reusing an integer variable: the cost to maintainabilty heavily outweighs the runtime cost savings.
0

Share this post


Link to post
Share on other sites
[quote name='Bregma' timestamp='1350063318' post='4989531']
[quote name='frob' timestamp='1350061504' post='4989518']
Please reread my post. No, they are not heavyweight. They are reusable.
[/quote]
Sure, they're reusable, but the heavy cost is in the open operation, not the object creation operation (except when the object creation includes the open operation).

Reusing an fstream is like reusing an integer variable: the cost to maintainabilty heavily outweighs the runtime cost savings.
[/quote]
The point was not about reuse cost.

The point was that sometimes a "reset this object" function is a good thing.
0

Share this post


Link to post
Share on other sites
Another (unfortunate) reason for needing a Cleanup() or Initialize() function is from poor third-party API designs that you have to work around in your own code. [img]http://public.gamedev.net//public/style_emoticons/default/dry.png[/img]

[quote name='frob' timestamp='1350053843' post='4989484']
It also makes sense for reusable objects, especially heavyweight objects that are expensive to create and destroy, but cheap to recycle.

An example of reusable objects would be the C++ file streams. You can use it once by create, open, close, then destroy; or reuse with create, open, close, open, close, open, close, ... etc., then destroy.
[/quote]
And conveniently, (some of) the constructors call open(), and the destructors call close() for you, so actual use can look like: create, destroy, or create, open, destroy, or create, close, open, destroy. Very nice design - very flexible.

Another benefit of that, is it makes the destructor and constructor implementation cleaner, especially when you have multiple constructors (and don't yet have constructor chaining).
[code]MyFile::MyFile()
{

}

MyFile::MyFile(filename)
{
this->Open(filename);
}

My::MyFile(data)
{
this->OpenFromData(data);
}

MyFile::Open(filename)
{
data = ::LoadFileData(filename);
this->OpenFromData(data);
}

MyFile::OpenFromData(data)
{
//actual loading from data...
}
[/code]

[b]Edit:[/b] Bah, code boxes messing up. [img]http://public.gamedev.net//public/style_emoticons/default/rolleyes.gif[/img] Edited by Servant of the Lord
2

Share this post


Link to post
Share on other sites
[quote name='frob' timestamp='1350063552' post='4989536']
The point was that sometimes a "reset this object" function is a good thing.[/quote]
And that's precisely the point I am questioning.

If the object had steep construction cost, then by all means, (carefully) provide reset/reuse functionality. But that is the only case in which I see it as a good thing.
0

Share this post


Link to post
Share on other sites
If you have global objects that requires other objects to be initialized or destroyed before initializing or destroying themselves, init() cleanUp() comes in handy.

[source lang="cpp"]MemoryManager memoryManager; //memoryManager must be initialized before other objects
RenderManager renderManager; //but c++ doesn't guarantee that memoryManager gets
AIManager aiManager; //initialized in the order it appears in the source code
[/source]
In this case we can make constructors and destructors do nothing and put init() and cleanUp() instead to ensure the order.
[source lang="cpp"]MemoryManager memoryManager;
RenderManager renderManager;
AIManager aiManager;// constructors do nothing here

int main()
{
memoryManager.init();
renderManager.init();
aiManager.init();

//Game Running...............
//game over-shut things down
aiManager.cleanUp();
renderManager.cleanUp();
memoryManager.cleanUp();
return 0;
}[/source] Edited by lride
1

Share this post


Link to post
Share on other sites
[b]Re: Constructor vs Init()[/b]

Because sometimes they are 2 different concepts.

A lot of my game objects just call a Reset()/Init() function in their constructor because I will reset them to an initial state over the course of their lifetime. A lot of times because there is a fixed number of them, and they disappear and reappear on a frequent basis. By calling Reset, I effectively create a new one, instead of allocating and de-allocating a new instance of an object for nothing. Also, sometimes I need to clear out references and other things that are no longer valid. A re-used object doesn't have a last attacker or a target yet. :)

I've also used it for particles. When a particle dies, it gets Reset(). Which means it returns to the origin, and then re-assigns itself some random properties as if it was a new instance. Edited by Daaark
0

Share this post


Link to post
Share on other sites
frob and Cornstalks gave the correct answers.

Here is an excerpt from my engine. A basic std::vector class:
The constructor:
[CODE] LSE_CALL CSVectorCrtp() :
m_tLen( 0 ),
m_tAllocated( 0 ),
m_ptData( NULL ) {
}[/CODE]
The Reset function:
[CODE] /**
* Reset the list completely. Frees all memory.
*/
LSVOID LSE_CALL Reset() {
for ( LSINT32 I = static_cast<LSINT32>(m_tLen); --I >= 0; ) {
Destroy( static_cast<_tDataType>(I) );
}
m_paDefaultAllocator->Free( m_ptData );
m_ptData = NULL;
m_tLen = m_tAllocated = 0;
}[/CODE]
The destructor:
[CODE] LSE_CALL ~CSVectorCrtp() {
Reset();
}[/CODE]


There is no harm done in the fact that it can easily be reused. Anyone who argues otherwise should swiftly be ignored.
It can obviously be used on a normal one-off basis, as is standard, but it is such a general-purpose class that who is to say it will never be useful to reuse the same object?
I personally do it all the time. It is just another option for our convenience and control.

Speaking of control:
[CODE] /**
* Reset the list without deallocating the whole buffer.
*/
LSVOID LSE_CALL ResetNoDealloc() {
for ( LSINT32 I = static_cast<LSINT32>(m_tLen); --I >= 0; ) {
Destroy( static_cast<_tDataType>(I) );
}
m_tLen = 0;
}[/CODE]
While there are ways to control std::vector to achieve the same results, they are fairly non-intuitive. It is a lot easier to just use Reset() and ResetNoDealloc(),which have obvious meanings.


Reusable classes are never a bad thing. They are just another layer of options, and that is always a good thing.


L. Spiro Edited by L. Spiro
1

Share this post


Link to post
Share on other sites
yes, from C# object gets anownced that it would like to be freed (By OS manager GC). You then perform alll logic to free resources the object posesss. Like sicrane said, study cli/c++

in c++ destrocturos are not necesary, nor any good logic, from C#, managememet of memory yes

You can still design your logic to not need destructors, but your logic must be freed and managed well
-9

Share this post


Link to post
Share on other sites
[quote name='JohnnyCode' timestamp='1350101946' post='4989668']
yes, from C# object gets anownced that it would like to be freed (By OS manager GC). You then perform alll logic to free resources the object posesss. Like sicrane said, study cli/c++

in c++ destrocturos are not necesary, nor any good logic, from C#, managememet of memory yes

You can still design your logic to not need destructors, but your logic must be freed and managed well
[/quote]

I really, really hope you don't use C++ exceptions.
1

Share this post


Link to post
Share on other sites
[quote name='InvalidPointer' timestamp='1350362505' post='4990618']
[quote name='JohnnyCode' timestamp='1350101946' post='4989668']
yes, from C# object gets anownced that it would like to be freed (By OS manager GC). You then perform alll logic to free resources the object posesss. Like sicrane said, study cli/c++

in c++ destrocturos are not necesary, nor any good logic, from C#, managememet of memory yes

You can still design your logic to not need destructors, but your logic must be freed and managed well
[/quote]

I really, really hope you don't use C++ exceptions.
[/quote]

Why shouldn't one use exceptions in C++? Edited by simpler
0

Share this post


Link to post
Share on other sites
If you use exceptions and not destructors (as JohnnyCode 'suggested') you will have one hell of a time doing resource management. InvalidPointer makes no point beyond that. He neither said you should nor should not use exceptions.
2

Share this post


Link to post
Share on other sites
[quote name='simpler' timestamp='1350383549' post='4990676']
[quote name='InvalidPointer' timestamp='1350362505' post='4990618']
[quote name='JohnnyCode' timestamp='1350101946' post='4989668']
yes, from C# object gets anownced that it would like to be freed (By OS manager GC). You then perform alll logic to free resources the object posesss. Like sicrane said, study cli/c++

in c++ destrocturos are not necesary, nor any good logic, from C#, managememet of memory yes

You can still design your logic to not need destructors, but your logic must be freed and managed well
[/quote]

I really, really hope you don't use C++ exceptions.
[/quote]

Why shouldn't one use exceptions in C++?
[/quote]

They can carry some very subtle, complicated costs and require some extra thinking when designing algorithms and classes. For games I don't really think they're worth said cost; in most cases using error codes can work equally well and can 're-enable' more dangerous (but speedier) class architectures. The latter is why I bring things up-- the C++ spec says the compiler will walk up the call stack, invoking destructors on everything until it finds an appropriate catch block. If you don't release any resources in the destructor, congratulations! You've just created a pretty massive, totally unfixable memory leak.

EDIT: [s]That also means that using raw allocations on the stack, anywhere, is unsafe. Consider the implications[/s]. Overloading operator new can help you in limited cases, come to think of it. If you don't, though, you're in trouble. Edited by InvalidPointer
0

Share this post


Link to post
Share on other sites
[quote name='InvalidPointer' timestamp='1350396279' post='4990718']
[quote]
Why shouldn't one use exceptions in C++?
[/quote]
They can carry some very subtle, complicated costs and require some extra thinking when designing algorithms and classes. For games I don't really think they're worth said cost; in most cases using error codes can work equally well and can 're-enable' more dangerous (but speedier) class architectures. The latter is why I bring things up-- the C++ spec says the compiler will walk up the call stack, invoking destructors on everything until it finds an appropriate catch block. If you don't release any resources in the destructor, congratulations! You've just created a pretty massive, totally unfixable memory leak.
[/quote]
The cost of designing using object-oriented techniques, including exceptions, is no greater than procedural techniques and propagating error codes, unless and except if you are more familiar with one or the other. This is not a technical issue, but a personal or social issue.

It is easier to leak resources using procedural programming in which you need to handle releases nonlocally as you manually unwind the stack than it is using OO techniques in which the purpose of the destructor is to release resources. Sure, you can write bad code using any paradigm. You are [i]less[/i] likely to write that particular kind of bad code using OO than procedural.

The third argument for using manual stack unwinding and error code propagation vs. exceptions is that you can write faster, simpler code with the manual method, because you just skip the error checks and cleanup code. You see a lot of that kind of code thrown up as examples of why exceptions are undesirable. I find it unconvincing.

The only really legitimate argument I've heard against using clean OO design with exceptions is that they're not supported by some runtimes. Now [i]that[/i] seems fair to me, although the fact that they've been supported by C++ longer than most of the posters on these forums have been alive makes it seem to me that the vendor's decision on that front has been politically motivated.
2

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