Reputation: 4920
lets say I have
class : foo
{
public:
static const foo Invalidfoo;
foo();
foo(int, string);
private:
int number;
std::string name;
};
Is it safe or prone to any problem?
EDIT :
I want to use this to have an invalid object to return as a reference to launch errors.
Upvotes: 1
Views: 1552
Reputation: 21398
It is perfectly legal, but the following is better:
class foo:
{
public:
static const& foo Invalidfoo()
{
static foo Invalidfoo_;
return Invalidfoo_;
}
private:
foo();
};
This way you are guaranteed that the object is initialized the first time it is used.
Edit: But no matter how you do it, you still have a global object, and that can be a cause of problem. The best solution may be to call the default constructor each time you need a default constructed object. In terms of efficiency, the difference is probably negligable.
Upvotes: 3
Reputation: 5963
This is actually how a singleton is implemented, except your static member would be a pointer. So yes, you're safe.
Upvotes: 0
Reputation: 361472
That is perfectly valid code. It doesn't have any reason to cause any problem, because static data members don't contribute to the size of the class. No matter how many static data members you define in a class, it doesn't change its size by even one byte!
struct A
{
int i;
char c;
};
struct B
{
int i;
char c;
static A a;
static B b;
};
In above code, sizeof(A) == sizeof(B)
will always be true. See this demo:
Its supported by the section $9.4.2/1 from the C++ Standard (2003),
A static data member is not part of the subobjects of a class. There is only one copy of a static data member shared by all the objects of the class.
You cannot define non-static data member of the enclosing class type, because non-static members are parts of the object, and so they do contribute to the size of the class. It causes problem when calculating the size of the class, due to recursive nature of the data members.
See this topic:
Upvotes: 1
Reputation: 146930
It's legal. Terrible code from a practical/style point of view, but it is legal, and technically, it can be made to work. Better than Singleton because it's immutable.
Upvotes: 0
Reputation: 190943
It is just acting like a global variable or singleton. It's prone to the problems relating to those.
Upvotes: 1
Reputation: 49251
It's legal.
It's actually widely used in the singleton pattern
Singletons multi threading access and creation problems.
A nice article about this:
C++ and the Perils of Double-Checked Locking
Upvotes: 3