Re: Passing Pointers -- where to delete them
On Mar 3, 12:37 am, Arv <arvind.b...@gmail.com> wrote:
I got most things clarified now, but I still have a doubt related to
shared_ptr. When I use a singleton object, would a shared_ptr help?
Not really, because:
Because when I use new inside the singleton's getInstance method, I am
not sure when to delete it, since it is a static member, i am not sure
putting the delete in the destructor would help. Should I have another
method called resetInstance or something?
Well, if it's a singleton, why would you want to reset it? ;-) But if
you must; you have a couple of options. You could do similar to what
you said, create a DeleteInstance() method or something that deletes
the single instance; and then call DeleteInstance() in your cleanup
code or wherever you want. For example:
----- BEGIN EXAMPLE1 -----
#include <cstdio>
class Singleton {
public:
static Singleton * GetInstance () {
if (!_s)
_s = new Singleton();
return _s;
}
static void DeleteInstance () {
delete _s;
_s = NULL;
}
void Hi (const char *where) {
printf("hello from %p in %s\n", (void *)this, where);
}
private:
Singleton () { printf("constructed @ %p\n", (void *)this); }
~Singleton () { printf("deleted\n"); }
static Singleton *_s;
};
Singleton * Singleton::_s;
void function () {
Singleton::GetInstance()->Hi("function");
}
int main (int, char **) {
// do a whole bunch of stuff
Singleton::GetInstance()->Hi("main");
function();
// delete on cleanup; maybe in an exit handler or somewhere else. or
here.
Singleton::DeleteInstance();
return 0;
}
----- END EXAMPLE1 -----
Using something like a boost::shared_ptr is not really necessary
there. Alternatively, you can do it without new at all:
----- BEGIN EXAMPLE2 -----
#include <cstdio>
class Singleton {
public:
static Singleton * GetInstance () {
static Singleton s; // <--- initialized first time here.
return &s;
}
void Hi (const char *where) {
printf("hello from %p in %s\n", (void *)this, where);
}
private:
Singleton () { printf("constructed @ %p\n", (void *)this); }
~Singleton () { printf("deleted\n"); }
};
void function () {
Singleton::GetInstance()->Hi("function");
}
int main (int, char **) {
// do a whole bunch of stuff
Singleton::GetInstance()->Hi("main");
function();
return 0;
}
----- END EXAMPLE2 -----
In that case you can't just "reset" the instance whenever you feel
like it (which, if you have to do this, you should consider whether or
not the "singleton" model is actually what you want), but it will call
the destructor when the program terminates.
Just out of curiosity: what are you doing that you want to use a
singleton class for?
Jason