Reputation: 25
my code below is not comiling for the singleton pattern
(error LNK2019: unresolved external symbol "private: __thiscall Singleton::Singleton(void)" (??0Singleton@@AAE@XZ) referenced in function "public: static class Singleton * __cdecl Singleton::returnOneInstance(void)" (?returnOneInstance@Singleton@@SAPAV1@XZ))
can anyone help? i also want to know how one must manage the memory? thanks
#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;
}
Upvotes: 1
Views: 248
Reputation: 17345
Basically the ctr has not been defined. I fixed this by adding the {} empty body. In this case you have just once instance of the object so there's no memory management unless you would like to free up the memory of the singleton. In this case you can provide to destroy the class and delete the reserved memory.
Following is your code fixed:
#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;
}
Upvotes: 1