Click here to Skip to main content
12,997,038 members (56,445 online)
Rate this:
Please Sign up or sign in to vote.
See more:
#include <iostream>
using namespace std;
template <class T>class X{
static X* getI()
   if (!pI)
    pI = new X;
   return pI;
typedef int err;
void set(int i) { oo = i;}
int get() { return oo; }
static X* pI;
err oo;
template <class T> X<T>* X<T>::pI = NULL;
int main()
X<int> *xx = X<int>::getI();
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 27-Feb-13 2:29am
Updated 27-Feb-13 3:21am
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! :)
Rate this: bad
Please Sign up or sign in to vote.

Solution 3

[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:

static X* getI()
   static X pIX;
   return &pIX;

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

(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.
Rate this: bad
Please Sign up or sign in to vote.

Solution 2

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:
friend int main();

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

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

  Print Answers RSS
Top Experts
Last 24hrsThis month

Advertise | Privacy | Mobile
Web02 | 2.8.170622.1 | Last Updated 27 Feb 2013
Copyright © CodeProject, 1999-2017
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100