- Game Development Patterns and Best Practices
- John P. Doran Matt Casanova
- 400字
- 2021-07-02 23:43:46
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.
- Android應用程序開發與典型案例
- Vue.js入門與商城開發實戰
- Web Application Development with R Using Shiny(Second Edition)
- Elasticsearch for Hadoop
- 利用Python進行數據分析(原書第3版)
- Python編程:從入門到實踐
- 第一行代碼 C語言(視頻講解版)
- Learning Apache Cassandra
- OpenGL Data Visualization Cookbook
- C#程序設計(項目教學版)
- PyQt編程快速上手
- iOS開發項目化入門教程
- ABAQUS6.14中文版有限元分析與實例詳解
- Mastering Embedded Linux Programming
- 3ds Max 2018從入門到精通