usage of static member as a class typein C++
Based on "c++ primer", the type of a static data member can be the class type of which it is a member:
class Bar {
public:
// ...
private:
static Bar mem1; // ok
};
However, I hav开发者_开发百科e a hard time imagining a scenario in which such a feature is useful. I mean, why do you need a variable to be the class type? Can someone give me some examples? Thank you.
The only time that this would really be useful would be in implementing the "Singleton" pattern (or "Simpleton" to those of us who despise it).
Singleton is one possible use. Another possible use is to provide one pre-packaged ready-to-use instance.
Suppose your class has expensive constructor, uses tons of memory and you need to create many instances. The good news is most of the instances are identical. You could make the most widely used copy static and reuse it whenever needed.
Example. Bar can be constructed from an integer. An instance constructed from 0 is in high demand. It is a good candidate to be made static.
class Bar {
public:
Bar(int n) : n_bar(n) {
// if n!=0, construct new instance of Bar, else recycle static instance
}
void foo() const { // note, it is const
if(n_bar==0)
bar0.foo();
else {
// do something
}
}
private:
int n_bar;
static Bar bar0; // initialize to Bar(0)
};
Instead of one static member, you can also create a whole battery of static instances (using std::map with ints as keys and Bars as values) on demand.
singleton
when you have some class that needs to have exactly one instance available globally. using a global variable doesn't restrict to single instance and can have problems with static inialization
one word: singleton.
精彩评论