Assuming this implementation of a singleton pattern ( of course we should avoid Singleton: it is just question), I have just been thinking about static object being created. It is created on heap by a new
operator, sure, but how is this destroyed? In following example we have a leak, so how one should implement deletion of static singleton object? Should there be a please_delete()
public interface adopted, so one can call myC->please_delete()
or is there other way to achieve this?
class CC{
public:
static CC* cObj(){
if(c_ptr==NULL){
c_ptr=new CC();
return c_ptr;
}else return c_ptr;
}
int getValue(){return value_;}
void setValue(int val){value_=val;}
~CC(){cout<<"~CC";}
private:
CC():value_(12345){cout<<"CC";}
static CC* c_ptr;
int value_;
};
// Allocating and initializing CC's
// static data member. The pointer is being
// allocated - not the object itself.
CC *CC::c_ptr = 0;
int main(){
//Singleton pattern
CC* myC = CC::cObj();
cout<<myC->getValue();
return 0;
}
output: CC12345
RUN SUCCESSFUL (total time: 67ms)
I noticed that indeed we can always declare singleton static instance within shared_ptr
as with boost::shared_ptr<CC> bCptr(CC::cObj());
but Singleton pattern doesn't mention the problem of deletion of the object at all so maybe there exists some other approach?
static CC
? – Pubby