c++单例模式_实现和内存管理
C++ singleton Pattern _ Implementation and memory managenet
下面的代码不能编译为单例模式
(错误LNK2019:未解析的外部符号"private: __thiscall Singleton::Singleton(void)")(??0Singleton@@AAE@XZ)引用函数"public: static class Singleton * __cdecl Singleton::returnOneInstance(void)"(? returnOneInstance@Singleton@@SAPAV1@XZ))
有人能帮忙吗?我还想知道一个人必须如何管理内存?由于
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <iterator>
using namespace std;
class Singleton
{
private:
Singleton();
Singleton(const Singleton& sing);
void operator=(const Singleton& sing);
static Singleton* singleton;
/*The 'instance' field holds the reference of the one and only instance.
It is stored in a static variable because its scope has to be the class itself and not a particular instance.
*/
public:
static Singleton* returnOneInstance();
void printme() const;
};
Singleton* Singleton::singleton=NULL;
Singleton* Singleton::returnOneInstance(){
if (!singleton){
singleton=new Singleton;
}
return singleton;
};
void Singleton::printme()const {
cout << "I'm the Singleton" << endl;
}
int main()
{
Singleton* m=Singleton::returnOneInstance();
m->printme();
system("PAUSE");
return 0;
}
基本上没有定义ctr。我通过添加{}空体来解决这个问题。在这种情况下,你只有一个对象的实例,所以没有内存管理,除非你想释放单例的内存。在这种情况下,您可以提供销毁类并删除保留的内存。
下面是你的代码修正:
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <iterator>
using namespace std;
class Singleton
{
private:
Singleton(){};
Singleton(const Singleton& sing);
void operator=(const Singleton& sing);
static Singleton* singleton;
/*The 'instance' field holds the reference of the one and only instance.
It is stored in a static variable because its scope has to be the class itself and not a particular instance.
*/
public:
static Singleton* returnOneInstance();
void printme() const;
};
Singleton* Singleton::singleton=NULL;
Singleton* Singleton::returnOneInstance()
{
if (!singleton){
singleton=new Singleton;
}
return singleton;
};
void Singleton::printme()const {
cout << "I'm the Singleton" << endl;
}
int main()
{
Singleton* m=Singleton::returnOneInstance();
m->printme();
system("PAUSE");
return 0;
}
相关文章:
- 当vector是tje全局变量时,c++中vector的内存管理
- 我有一个线程 1:EXC_BAD_ACCESS(代码 = 1,地址 = 0x8)错误.我认为这是由于内存管理不好.我可以
- C++将字符串传递给 C 库以进行内存管理
- 从函数返回时C++内存管理
- 函数指针和 lambda 的内存管理
- 自定义内存管理器在发布模式下工作正常,但在调试模式下则不然
- C++中的内存管理
- C和C++中的内存管理有什么区别
- 字符 * 未从重载运算符或内存管理问题正确返回
- 如何在源代码中使用执行策略检测 C++17 的扩展内存管理算法的可用性?
- 底层指针和内存管理
- 智能指针,避免使用QNetworkAccessManager时进行手动内存管理
- c++中的内存管理问题
- 使用矢量时的内存管理
- 循环和内存管理中的指针算术C++?
- C++堆栈内存管理问题
- C 内存管理中的课程如何管理 - 研究
- 不可变数据模型的内存管理
- C++ 使用数组初始化时的 STL 向量内存管理
- SFML 纹理内存管理