Archived

This topic is now archived and is closed to further replies.

Advantages of Singleton over Static Classes

This topic is 5749 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

What are the advantages of singleton classes over just making every member and method of the class static? Both methods seem to accomplish the same goal of getting around globals. No, HTML is not an OO language.

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
The order of static member variable construction is undefined by the C++ standard (and global construction for that matter). This means your in trouble if one of your static variables relies on the construction of another static variable in another class. For example:


  
class X
{
public:
static std::complex a;
};

std::complex X::a(1, 2);

class Y
{
public:
static std::complex b;
};

std::complex Y::b = X::a;


It may work correctly, it might not. If it did, you were lucky and you shouldn''t rely on it.

The only way around is to construct the object when it is needed:


  
class X
{
public:
static std::complex get()
{
static std::complex a(1, 2);

return a;
}
}

std::complex X::a(1, 2);

class Y
{
public:
static std::complex b;
}

std::complex Y::b = X::get();


Some people use dynamic memory for this kind of thing but that''s just messy and should be avoided.

However, if your sure you won''t suffer from this problem, you could happily just use a class with only static members. It might just be safer to use the Singleton pattern though, because it saves you having to change back later if you discover a problem.

Share this post


Link to post
Share on other sites