c++单例模式_实现和内存管理

C++ singleton Pattern _ Implementation and memory managenet

本文关键字:内存 管理 实现 单例模式 c++      更新时间:2023-10-16

下面的代码不能编译为单例模式

(错误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;
}