CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Page 1 of 2 12 LastLast
Results 1 to 15 of 29
  1. #1
    Join Date
    Jul 2005
    Posts
    1,030

    A question regarding singleton

    Here is a simple implementation of singleton,
    Code:
    class A
    {
    private:
    	A(int x) : _x(x)
    	{
    	}
        int _x;
    
    	friend A& createA(int x)
    	{
    		static A a(x);
    		return a;
    	}
    };
    
    int main()
    {
    	A a1 = createA(1);
    	A a2 = createA(2);
    
    	return 0;
    }
    By debugging, I found that a1._x = 1 and a2._x = 1. It looks like only one object is created. But I wonder why returning static object a can guarantee only one object is created.

  2. #2
    Join Date
    Jun 2010
    Location
    Germany
    Posts
    2,675

    Re: A question regarding singleton

    Aside from the fact that your creator function needs to be static instead of friend...

    Quote Originally Posted by LarryChen View Post
    By debugging, I found that a1._x = 1 and a2._x = 1. It looks like only one object is created.
    Creating only one object is the intention behind a singleton. Your creator function instantiates the static variable only once when it is first called, and subsequentially just returns a reference to that very instance.

    But I wonder why returning static object a can guarantee only one object is created.
    Just returning a reference to a static doesn't do that. Your objects a1 and a2 are actually copies (created by the compiler-generated default copy constructor) of the "singleton" object, thus breaking the singleton concept. You can simply check that by assigning something to the _x member of one of the objects in main() (after making that member public).

    You need not only to return a reference, you also need to initialize references from it instead of making copies. To enforce that you need to declare a private copy constructor and assignment operator which disables copying and assignment.

    BTW, an alternative to returning a reference in the singleton pattern is to return a pointer to the single reference. But that doesn't change anything about the principle.
    I was thrown out of college for cheating on the metaphysics exam; I looked into the soul of the boy sitting next to me.

    This is a snakeskin jacket! And for me it's a symbol of my individuality, and my belief... in personal freedom.

  3. #3
    Join Date
    Aug 2007
    Posts
    858

    Re: A question regarding singleton

    But I wonder why returning static object a can guarantee only one object is created.
    What you have there isn't really a singleton... it's something more like a factory. Only one A exists within the createA() function (thanks to it being static), but you have more than one A in your program (three of them, in fact). You're just forced to create them by calling createA().

  4. #4
    Join Date
    Jul 2005
    Posts
    1,030

    Re: A question regarding singleton

    [QUOTE=Eri523;2011149]Aside from the fact that your creator function needs to be static instead of friend...
    Why does the creator function need to be static? Take a look at the following implementation,
    Code:
    class A
    {
    private:
    	A(int x) : _x(x)
    	{
    	}
    
    	A(const A&){}
    
    	operator=(const A&){}
    
        int _x;
    
        friend A& createA(int x)
    	{
    		static A a(x);
    		return a;
    	}
    };
    Is there anything wrong? Thanks.

  5. #5
    Join Date
    Jan 2006
    Location
    Singapore
    Posts
    6,765

    Re: A question regarding singleton

    Quote Originally Posted by LarryChen
    Why does the creator function need to be static?
    It doesn't need to be a static member function, but with such factory functions it is more conventional to write:
    Code:
    A a1 = A.create(1);
    rather than
    Code:
    A a1 = createA(1);
    unless createA can be a non-member non-friend.
    C + C++ Compiler: MinGW port of GCC
    Build + Version Control System: SCons + Bazaar

    Look up a C/C++ Reference and learn How To Ask Questions The Smart Way
    Kindly rate my posts if you found them useful

  6. #6
    Join Date
    Jun 2010
    Location
    Germany
    Posts
    2,675

    Re: A question regarding singleton

    Quote Originally Posted by LarryChen View Post
    Take a look at the following implementation,

    [...]

    Is there anything wrong? Thanks.
    Did you actually try to compile that?

    Aside from that, I see absolutely no point in making a member function a friend of its own class.
    I was thrown out of college for cheating on the metaphysics exam; I looked into the soul of the boy sitting next to me.

    This is a snakeskin jacket! And for me it's a symbol of my individuality, and my belief... in personal freedom.

  7. #7
    Join Date
    Jan 2006
    Location
    Singapore
    Posts
    6,765

    Re: A question regarding singleton

    Quote Originally Posted by Eri523
    I see absolutely no point in making a member function a friend of its own class.
    I do not think it is possible to make a member function a friend of its own class.
    C + C++ Compiler: MinGW port of GCC
    Build + Version Control System: SCons + Bazaar

    Look up a C/C++ Reference and learn How To Ask Questions The Smart Way
    Kindly rate my posts if you found them useful

  8. #8
    Join Date
    Jun 2010
    Location
    Germany
    Posts
    2,675

    Re: A question regarding singleton

    Quote Originally Posted by laserlight View Post
    It doesn't need to be a static member function [...]
    To my understanding a singleton instance accessor that is a non-static member of the singleton is completely paradox. Ths instance accessor can be a non-static class member, but then of another class, at least as I understand the description at http://en.wikipedia.org/wiki/Singlet...method_pattern.

    I think it's also possible to make the instance accessor a free friend function of the singleton, but then it would still implicitly be static.

    Quote Originally Posted by laserlight View Post
    I do not think it is possible to make a member function a friend of its own class.
    To my surprise, the following actually does compile under VC++ 2010:

    Code:
    #include <iostream>
    
    using namespace std;
    
    class B
    {
    public:
      B() : m_x(23)
      {}
    
    private:
      friend int getx(const B &b_)
      {
        return b_.m_x;
      }
    
      int m_x;
    };
    
    int main()
    {
      B b;
      cout << getx(b) << endl;
      return 0;
    }
    But note that in this scenario getx() actually is a disguised free function.
    I was thrown out of college for cheating on the metaphysics exam; I looked into the soul of the boy sitting next to me.

    This is a snakeskin jacket! And for me it's a symbol of my individuality, and my belief... in personal freedom.

  9. #9
    Join Date
    Oct 2006
    Location
    Sweden
    Posts
    3,654

    Re: A question regarding singleton

    Is it that disguised? After all we all expect a friend function to be a free function so isn't this more about where it's implemented?
    I think laserligths statement still is true since it should be impossible to implement it as B::getx
    Debugging is twice as hard as writing the code in the first place.
    Therefore, if you write the code as cleverly as possible, you are, by
    definition, not smart enough to debug it.
    - Brian W. Kernighan

    To enhance your chance's of getting an answer be sure to read
    http://www.codeguru.com/forum/announ...nouncementid=6
    and http://www.codeguru.com/forum/showthread.php?t=366302 before posting

    Refresh your memory on formatting tags here
    http://www.codeguru.com/forum/misc.php?do=bbcode

    Get your free MS compiler here
    https://visualstudio.microsoft.com/vs

  10. #10
    Join Date
    Jun 2010
    Location
    Germany
    Posts
    2,675

    Re: A question regarding singleton

    Quote Originally Posted by S_M_A View Post
    I think laserligths statement still is true since it should be impossible to implement it as B::getx
    I agree. That code is just my attempt to find out the OP's (potential) intention behind the (non-compiling) code from post #1 and how it might be turned into something that actually does compile, mostly regardless of what would then be the result of that compilation, or better, trying to find out what that result then would be.
    I was thrown out of college for cheating on the metaphysics exam; I looked into the soul of the boy sitting next to me.

    This is a snakeskin jacket! And for me it's a symbol of my individuality, and my belief... in personal freedom.

  11. #11
    Join Date
    Oct 2006
    Location
    Sweden
    Posts
    3,654

    Re: A question regarding singleton

    And that's absolutely nothing to be embarressed for and that wasn't my intention either. I was just happy that I had knowledge enough to be part of the thread.
    Debugging is twice as hard as writing the code in the first place.
    Therefore, if you write the code as cleverly as possible, you are, by
    definition, not smart enough to debug it.
    - Brian W. Kernighan

    To enhance your chance's of getting an answer be sure to read
    http://www.codeguru.com/forum/announ...nouncementid=6
    and http://www.codeguru.com/forum/showthread.php?t=366302 before posting

    Refresh your memory on formatting tags here
    http://www.codeguru.com/forum/misc.php?do=bbcode

    Get your free MS compiler here
    https://visualstudio.microsoft.com/vs

  12. #12
    Join Date
    Jun 2010
    Location
    Germany
    Posts
    2,675

    Re: A question regarding singleton

    Update: The Comeau compiler accepted the code from post #8 without any complaints as well.
    I was thrown out of college for cheating on the metaphysics exam; I looked into the soul of the boy sitting next to me.

    This is a snakeskin jacket! And for me it's a symbol of my individuality, and my belief... in personal freedom.

  13. #13
    Join Date
    Jan 2006
    Location
    Singapore
    Posts
    6,765

    Re: A question regarding singleton

    Quote Originally Posted by Eri523
    To my understanding a singleton instance accessor that is a non-static member of the singleton is completely paradox.
    A non-member function is also not a static member function

    In fact, that is how I understood the point that LarryChen was making. It seemed to me that LarryChen correctly identified the friend function createA as a non-member function, despite it being defined within the definition of a class.

    Quote Originally Posted by Eri523
    I think it's also possible to make the instance accessor a free friend function of the singleton, but then it would still implicitly be static.
    No, it wouldn't implicitly be static, because the static specifier as applied to free functions has a different, though related, meaning.
    C + C++ Compiler: MinGW port of GCC
    Build + Version Control System: SCons + Bazaar

    Look up a C/C++ Reference and learn How To Ask Questions The Smart Way
    Kindly rate my posts if you found them useful

  14. #14
    Join Date
    Jun 2010
    Location
    Germany
    Posts
    2,675

    Red face Re: A question regarding singleton

    Ah, I'm gradually getting it... I obviously misinterpreted your sentence:

    Quote Originally Posted by laserlight View Post
    It doesn't need to be a static member function [...].
    You actually meant it doesn't need to be a member at all (which of course is absolutely right) and I interpreted that as "it needs to be a member, just not static". This misunderstanding probably got some extra promotion from the fact that I myself actually prefer static member instance accessors because I find they make it more obvious what they're intended for.

    Quote Originally Posted by laserlight View Post
    A non-member function is also not a static member function

    [...]

    No, it wouldn't implicitly be static, because the static specifier as applied to free functions has a different, though related, meaning.
    Looks like another communication problem, this time of type "terminology clash"... And it's clearly my own fault. With respect to the topic of this thread, I more or less intentionally misused the word static. I used it with the meaning "not object-bound" but of course it has another meaning for free functions. When I wrote it I was assuming it was perfectly clear and understandable what I meant, but obviously I was sooo wrong...
    I was thrown out of college for cheating on the metaphysics exam; I looked into the soul of the boy sitting next to me.

    This is a snakeskin jacket! And for me it's a symbol of my individuality, and my belief... in personal freedom.

  15. #15
    Join Date
    Jan 2010
    Posts
    1,133

    Re: A question regarding singleton

    Quote Originally Posted by laserlight View Post
    It seemed to me that LarryChen correctly identified the friend function createA as a non-member function, despite it being defined within the definition of a class.
    I'm not saying you're wrong, and my intention is entirely to learn something, but, from an OO design point of view: how can a function the enclosing context of which is a class not be a member function of that class?
    Is this something C++ specific? (My weapon of choice is C#, so - maybe I'm missing something...) Or maybe the words "member function" have a slightly different meaning for us?

Page 1 of 2 12 LastLast

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured