Click here to Skip to main content
15,891,704 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
C++
#include <iostream>
using namespace std;

template <class T>class X{
public:
static X* getI()
{
   if (!pI)
    pI = new X;
   return pI;
}
typedef int err;
void set(int i) { oo = i;}
int get() { return oo; }
private:
X(){}
~X(){}
static X* pI;
err oo;
};
template <class T> X<T>* X<T>::pI = NULL;

int main()
{
X<int> *xx = X<int>::getI();
xx->set(11);
cout << xx->get();
if (xx)
 delete xx;
return 0;
}



I am getting below error while executing this code piece:
In function int main();:
Line 18: error: ~X() [with T = int]; is private
I want to keep Contructor & Destructor in private.

Please help me resolve the issue. Thx.
Posted
Updated 27-Feb-13 3:21am
v3
Comments
max_nowak 27-Feb-13 9:20am    
I'm sorry, I just postet an answer but then deleted, because I realized I was plain stupid
Member 8576081 27-Feb-13 23:31pm    
:) Thanks for your time anyways! :)

[Solution #2 has good info.]

This is C++. You could just make a static instance inside the get() method. This would prevent the need for or access to a destructor (but this would be taken care of at program exit). In other words:

C++
static X* getI()
{
   static X pIX;
   return &pIX;
}


[you can't do this in java for example.]

Also
(1) this is not threadsafe (which may or may not be an issue for you). If you have multiple threads, the construction (at least) should be protected with a critical section so you don't get 2 or more messed up instances.
(2) you don't need to do "if(x) delete x;" - just "delete x;" ... you don't need to check if the pointer is NULL.
 
Share this answer
 
In main you're calling delete, and that requires the destructor to be public.

If you want to clean up your singletons, you must provide at least one (public) way to destroy the instance. A possible solution would be to declare main() a friend of the singleton class:
C++
friend int main();


Of course, you could simply choose not to free those singletons - the memory will be freed anyway when the application exits.
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900