Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: C++
Expertise: Beginner
May 2, 1997

Constructor with static members in library

Question:
Background: Digital UNIX 3.2g, Alpha platform, latest GNU.

From the FAQ, I know that you are supposed to declare static member variables externally from the declaration and in only one place. But our group has run into a problem with that.

The code below works fine when it's just a couple of normal files compiled together. But what to do when that class is part of a library? Defining it in the related source causes us core dumps, which we traced to the fact that the static member class constructors did not run when placed in the library. If the static member class variables are defined in the main program, everything works fine again, but it just plain feels wrong for the application to have intricate knowledge of library class internals. Is there a recommended method of doing what we are without "exposing ourselves"?

Here's a version of what I'm talking about in case my description lacked info or used poor terminology. The Test.C file would normally be part of the library.

Test.h
 ----------
class StaticTest {
public:
    StaticTest();
    ~StaticTest();
};

class MyContainer {
public:
    MyContainer();
    ~MyContainer();
private:
    static StaticTest _list [3];
    static StaticTest _single;
};


Test.C
 ----------
#include 
#include "Test.h"

StaticTest::StaticTest() { cerr << "StaticTest" << endl; }
StaticTest::~StaticTest() {}

#if LOOKS_GOOD_BUT_DOESNT_WORK
StaticTest MyContainer::_list[3];
StaticTest MyContainer::_single;
#endif

MyContainer::MyContainer() { cerr << "MyContainer" << endl; }
MyContainer::~MyContainer() {}


Main.C
 -----------
#include "Test.h"

#if WORKS_BUT_FEELS_WRONG
StaticTest MyContainer::_list[3];
StaticTest MyContainer::_single;
#endif

int main (int, char *[])
{
    MyContainer container;
    return 0;
}

Answer:
What you are trying to do is perfectly OK and normal..

I know of at least one platform (VxWorks) where these have to be treated specially because the platform requires it to be so.

I would like to know on what platform you tried to do this , so I can try to run it on the same and investigate the problem further C++Pro

DevX Pro
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date