Deleting our object correctly

People also are used to looking for memory leaks with pointers and not references, so that perhaps leaves us with an issue as, in our current code, we allocate memory but don't actually delete it.

Now, technically, we haven't created a memory leak. Memory leaks appear when you allocate data and lose all of your references to it. Also, modern operating systems take care of deallocating a process's memory when our project is quit.

That's not to say that it's a good thing though. Depending on what information the Singleton class uses, we could have references to things that no longer exist at some point.

To have our object delete itself correctly, we need to destroy the Singleton when our game shuts down. The only issue is we need to make sure that we do it only when we are sure no one will be using the Singleton afterwards.

However, as we want to talk about best practices, it's much better for us to actually solve this issue by removing resource leaks whenever we see them. A solution to this very problem was created by Scott Meyers in his book More Effective C++, which uses some of the features of the compiler, namely that a static variable located in a function will exist throughout our program's running time. For instance, let's take the following function:

void SpawnEnemy() 
{
static int numberOfEnemies = 0;
++numberOfEnemies;

// Spawn the enemy
}

The numberOfEnemies variable is created and has been initialized before any code in the project has been executed, most likely when the game was being loaded. Then, once SpawnEnemy is called for the first time, it will have already been set to 0 (or nullptr). Conveniently, as the object is not allocated dynamically, the compiler will also create code so that, when the game exists, it will call the deconstructor for our object automatically.

With that in mind, we can modify our Singleton class to the following:

class Singleton 
{
public:
static Singleton & GetInstance()
{
static Singleton instance;
return instance;
}

private:
// Disable usability of silently generated functions
Singleton();
~Singleton();
Singleton(const Singleton &);
Singleton& operator=(const Singleton&);

};

Specifically note the changes we've made to the GetInstance function and the removal of our class instance variable. This method provides the simplest way to destroy the Singleton class automatically and it works fine for most purposes.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.223.196.146