Re: [Dev-C++] singleton pattern implementation.
Open Source C & C++ IDE for Windows
Brought to you by:
claplace
|
From: Chris M. <lor...@gm...> - 2007-09-27 16:38:36
|
On 9/27/07, Laura Lozano <lau...@gm...> wrote:
> Hello,
>
> I have a question about the next implementation of the singleton patter, if
> I don't do "delete sc1" in main, is there a memory leak? the problem is
> that if I do in the destructor "delete single" it produces an infinite
> loop.
I'm not speaking from experience, but just thinking aloud.
You don't need to call delete in the destructor. Remember, a class is
literally just a bunch of locations in memory. If the destructor has
been called, delete has already been called (externally to the
destructor) as well. IIRC, it's your job to free all pointers to
locations in memory that are handled by the class in the destructor,
since those won't be freed automatically by delete.
> How could I free the memory associated to the variable single?
Perhaps use free(single)? I'm not sure, I know there are consequences
to mixing new/delete and malloc/free, but from my (rather limited)
knowledge I know that free() will just release memory back to the
system.
> Thank you.
>
> class Singleton
> {
>
private:
> static bool instanceFlag;
> static Singleton *single;
> Singleton()
> {
>
//private constructor
> }
> public:
> static Singleton* getInstance();
> void method();
> ~Singleton()
> {
> instanceFlag = false;
> }
> };
>
> bool Singleton::instanceFlag = false;
> Singleton* Singleton::single = NULL;
> Singleton* Singleton::getInstance()
> {
> if(! instanceFlag)
> {
> single = new Singleton();
> instanceFlag =
true;
> return single;
> }
> else
> {
> return single;
> }
> }
>
>
void Singleton::method()
> {
> cout << "Method of the singleton class" << endl;
> }
>
> int main()
> {
> Singleton *sc1;
> sc1 = Singleton::getInstance();
> sc1->method();
>
> return 0;
> }
>
>
> -------------------------------------------------------------------------
> This SF.net email is sponsored by: Microsoft
> Defy all challenges. Microsoft(R) Visual Studio 2005.
> http://clk.atdmt.com/MRT/go/vse0120000070mrt/direct/01/
> _______________________________________________
> Dev-cpp-users mailing list
> Dev...@li...
> TO UNSUBSCRIBE:
> http://www23.brinkster.com/noicys/devcpp/ub.htm
> https://lists.sourceforge.net/lists/listinfo/dev-cpp-users
>
>
--
Registered Linux Addict #431495
If You Know What's Good For You, You'll Install Linux
John 3:16!
|