Click here to Skip to main content
Rate this: bad
good
Please Sign up or sign in to vote.
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 27-Feb-13 2:29am
Edited 27-Feb-13 3:21am
v3
Comments
max_nowak at 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 at 27-Feb-13 23:31pm
   
:) Thanks for your time anyways! :)
Rate this: bad
good
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.]
 
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.
  Permalink  
Rate this: bad
good
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.
  Permalink  
v2

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

  Print Answers RSS
0 OriginalGriff 349
1 Sergey Alexandrovich Kryukov 319
2 Maciej Los 260
3 George Jonsson 185
4 King_Fisher 160
0 Sergey Alexandrovich Kryukov 10,934
1 Maciej Los 5,614
2 OriginalGriff 5,603
3 CPallini 3,879
4 BillWoodruff 3,579


Advertise | Privacy | Mobile
Web01 | 2.8.141030.1 | Last Updated 27 Feb 2013
Copyright © CodeProject, 1999-2014
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