
static member objects of templates - bug?
Quote:
> Hi All,
> It appears that static members of templates are constructed only after a
> template instance is constructed. Is this correct behaviour?.
14.7.1 Implicit instantiation
...the initialization (and any associated side-effects) of a static data member
does not occur unless the static data member is itself used in a way that
requires the definition of the static data member to exist.
I would expect that explicit instantiation of the static member should
do the job. Unfortunately your program crashes even with explicitly
instantiated static member (and this I think indeed is a bug).
Funny as it may look explicit specialization helps. See at the end of
this message.
Quote:
> Below is some example code that demonstrates (CShared constructor is
> called after CWrapper constructor - Only one message box is displayed -
> "Prepare to die").
> Any ideas about how to get around the problem?.
> I am using VC++ 6.0.
> Thanks for previous help,
> David.
> file://**************** The code ...
> class CShared
> {
> public:
> CShared()
> {
> MessageBox(NULL, _T("CShared Constructor"), _T(""), MB_OK);
> mMessage = _T("Joy To The World");
> }
> TCHAR GetChar()
> {
> return (*mMessage);
> }
> private:
> TCHAR* mMessage;
> };
> template<class Wrapped>
> class CWrapper
> {
> public:
> CWrapper()
> {
> MessageBox(NULL, _T("Prepare to die"), _T(""), MB_OK);
> /*
> * mSharedObject.mMessage should contain _T("Joy To The World")
> * at this point & lChar should be set to 'J'.
> */
> TCHAR lChar = mSharedObject.GetChar(); // this line crashes.
> MessageBox(NULL, _T("Never Gets Here"), _T(""), MB_OK);
> }
> protected:
> static CShared mSharedObject;
> };
> template <class Wrapped>
> CShared CWrapper<Wrapped>::mSharedObject;
> class CDummy
> {};
// this does not help
// template CShared CWrapper<CDummy>::sSharedObject;
// this does
template<> CShared CWrapper<CDummy>::sSharedObject;
Quote:
> // Constructing this object causes a crash.
> CWrapper<CDummy> gWrapped;
Sergei