For Programmers: Free Programming Magazines  


Home > Archive > VC STL > January 2006 > Re: declaring stl containers as static doesn't appear to work?? Is this how to implem









You are viewing an archived Text-only version of the thread. To view this thread in it's original format and/or if you want to reply to this thread please [click here]

 

Author Re: declaring stl containers as static doesn't appear to work?? Is this how to implem
tom_usenet@hotmail.com

2006-01-09, 11:10 pm


Simon L wrote:

> I've got a singleton class with a load a static functions and
> variables. It's basically a container for a class of objects
>
> #include <vector>
> using namespace std;
>
> class Groups
> {
> public:
>
> ~Groups(void);
> static Groups m_Group;
> Groups( LPCTSTR lpszName , eTYPE eType , CString strChildren );
> static void LoadGroups();
> static Groups* FindGroup(LPCTSTR lpszName);
>
> private:
> Groups(void);
> static vector<Groups*> m_vAllgroups;
> };
>
> //in .cpp
> Groups Groups::m_Group;
> vector<Groups*> Groups::m_Allgroups;


Swap the above two lines and all will be well.

> Now it seems to work OK unless I declare m_vAllgroups as static, in
> which case calls to push_back seem to work OK but when I get to a
> function needing an iterator, m_vAllgroups seems empty. Any ideas?


It's just an order of initialisation issue. Objects of static storage
duration are initialised in the order encountered (within a single
translation unit), so you need to initialise m_Allgroups before you
initialise anything that uses it (m_Group).

> Also, is this a good way to implement a singleton class? It means I can
> always access Groups::m_Group or any of the Groups data from anywhere
> in my application without having to pass pointers around.


Remember that singletons are global data (encapsulated, but still
global). Only use singletons for things that really are singletons and
that should be global (logging is one thing that springs to mind),
since unpicking the code if you ever need to support multiple sets of
Groups will be a pain in the neck. On the whole I think singletons
should be avoided much of the time, and the necessary "global" contexts
instead be passed to constructors and as function parameters to deal
with the case when they are no longer "global".

Tom

Sponsored Links







Also available: Server administration forum archive | Web Design forum archive | Software forum archive | Hardware reviews archive

Copyright 2008 codecomments.com