Protecting class from getting instantiated before main() - c++

I want to ensure that my C++ class is never instantiated before main() is entered. Is there any way to achieve this?
--
Some clarification:
I am writing an embedded application. My class must be static (reside in the BSS), but at instantiation it requires some resources that aren't available before certain things has been initialized in start of main(). So I want to make it a Meyers singleton. Ideally I would like to make some kind of assert that ensures that MyClass::instance() is never called before main().

Restricting construction of a class before some method gets called is going to be a losing battle. Especially if that method is main(). Can I ask why you have this requirement? Perhaps there is another way to tackle the actual problem you're attempting to solve.
Edit: thanks for the CTQ, and judging from it your best bet is probably the simplest solution, which is a static boolean. Since it's embedded I'm going to make the assumption that you pretty much control the entire environment. A simple assert in your ::instance() based on a static bool is probably all that you need.
Taking it one step further, It sounds like you need dependency injection or some other way of assuring that your resources are initialized in the correct order, which I'll be honest, is not a problem I've tackled in C++ (let alone on an embedded system). I can't give any additional insight into the most effective means for that case and would suggest you consider maybe one of the other answers to this question.

One thing you can do is have a static method like MyClass::enableConstruction() which turns on a static flag in the class. If the c'tor is called when this flag is false then it throws an exception. This way you'll alteast have some run-time indication that someone is breaking the rules.
Notice that you should be careful with the initialization of that static flag. To avoid any construction order problems it would probably be best to make it a singleton that is initialized when first accessed.

Give your class a static bool that is set on the first instantiation, and check it at the beginning of main()
Using a factory or making the constructor private will not stop it being instantiated in the constructor of a class that is instantiated before main()

There is no clean way to do this. Perhaps there's something hackish you can do to achieve this end, but you shouldn't.
Describe the fuller need and I'm certain a better solution can be found.

If you can control the code that gets executed when main() starts, then you can have a function like this:
bool wasMain (bool inMain = false) {
static bool passedMain = false;
return passedMain |= inMain;
}
Then, first line within main use wasMain(true) and it shall return true from there onwards, whereas it will return false until that point.
Edit: I just love shorter code, the above implementation can be simplified to:
bool wasMain (bool inMain = false) {
static bool passedMain = false;
if (inMain)
passedMain = true;
return passedMain;
}

One possible way is to instance the class inside main. i.e.
MyClass * g_thing = 0;
int main()
{
g_thing = new MyClass();
}
Other than that it's a tricky, compiler specific mess. What are you trying to achieve?

Related

Static variable from a static linked lib used before its construction [duplicate]

When I use static variables in C++, I often end up wanting to initialize one variable passing another to its constructor. In other words, I want to create static instances that depend on each other.
Within a single .cpp or .h file this is not a problem: the instances will be created in the order they are declared. However, when you want to initialize a static instance with an instance in another compilation unit, the order seems impossible to specify. The result is that, depending on the weather, it can happen that the instance that depends on another is constructed, and only afterwards the other instance is constructed. The result is that the first instance is initialized incorrectly.
Does anyone know how to ensure that static objects are created in the correct order? I have searched a long time for a solution, trying all of them (including the Schwarz Counter solution), but I begin to doubt there is one that really works.
One possibility is the trick with the static function member:
Type& globalObject()
{
static Type theOneAndOnlyInstance;
return theOneAndOnlyInstance;
}
Indeed, this does work. Regrettably, you have to write globalObject().MemberFunction(), instead of globalObject.MemberFunction(), resulting in somewhat confusing and inelegant client code.
Update: Thank you for your reactions. Regrettably, it indeed seems like I have answered my own question. I guess I'll have to learn to live with it...
You have answered your own question. Static initialization order is undefined, and the most elegant way around it (while still doing static initialization i.e. not refactoring it away completely) is to wrap the initialization in a function.
Read the C++ FAQ items starting from https://isocpp.org/wiki/faq/ctors#static-init-order
Maybe you should reconsider whether you need so many global static variables. While they can sometimes be useful, often it's much simpler to refactor them to a smaller local scope, especially if you find that some static variables depend on others.
But you're right, there's no way to ensure a particular order of initialization, and so if your heart is set on it, keeping the initialization in a function, like you mentioned, is probably the simplest way.
Most compilers (linkers) actually do support a (non-portable) way of specifying the order. For example, with visual studio you can use the init_seg pragma to arrange the initialization into several different groups. AFAIK there is no way to guarantee order WITHIN each group. Since this is non-portable you may want to consider if you can fix your design to not require it, but the option is out there.
Indeed, this does work. Regrettably, you have to write globalObject().MemberFunction(), instead of globalObject.MemberFunction(), resulting in somewhat confusing and inelegant client code.
But the most important thing is that it works, and that it is failure proof, ie. it is not easy to bypass the correct usage.
Program correctness should be your first priority. Also, IMHO, the () above is purely stylistic - ie. completely unimportant.
Depending on your platform, be careful of too much dynamic initialization. There is a relatively small amount of clean up that can take place for dynamic initializers (see here). You can solve this problem using a global object container that contains members different global objects. You therefore have:
Globals & getGlobals ()
{
static Globals cache;
return cache;
}
There is only one call to ~Globals() in order to clean up for all global objects in your program. In order to access a global you still have something like:
getGlobals().configuration.memberFunction ();
If you really wanted you could wrap this in a macro to save a tiny bit of typing using a macro:
#define GLOBAL(X) getGlobals().#X
GLOBAL(object).memberFunction ();
Although, this is just syntactic sugar on your initial solution.
dispite the age of this thread, I would like to propose the solution I've found.
As many have pointed out before of me, C++ doesn't provide any mechanism for static initialization ordering. What I propose is to encapsule each static member inside a static method of the class that in turn initialize the member and provide an access in an object-oriented fashion.
Let me give you an example, supposing we want to define the class named "Math" which, among the other members, contains "PI":
class Math {
public:
static const float Pi() {
static const float s_PI = 3.14f;
return s_PI;
}
}
s_PI will be initialized the first time Pi() method is invoked (in GCC). Be aware: the local objects with static storage have an implementation dependent lifecyle, for further detail check 6.7.4 in 2.
Static keyword, C++ Standard
Wrapping the static in a method will fix the order problem, but it isn't thread safe as others have pointed out but you can do this to also make it thread if that is a concern.
// File scope static pointer is thread safe and is initialized first.
static Type * theOneAndOnlyInstance = 0;
Type& globalObject()
{
if(theOneAndOnlyInstance == 0)
{
// Put mutex lock here for thread safety
theOneAndOnlyInstance = new Type();
}
return *theOneAndOnlyInstance;
}

Using std::hash<uint64_t> for custom class

Do the following two return statements return the same thing?
class NonTrivialClass
{
public:
size_t hash() const
{
// variation 1
return std::hash<uint64_t>::_Do_hash(my_val_);
// variation 2, wanted to avoid creating the named object
std::hash<uint64_t> hasher;
return hasher(my_val_);
}
private:
// relevant info for hashing purposes is stored here
uint64_t my_val_;
}
I intuitively wanted to write something like
return std::hash<uint_64>(my_val_);
which did not compile (because I didn't init an instance of the struct?!). Is there a another way I am missing? Is worrying about creating the named hasher struct unneccessary?
A simpler way of writing it is using a temporary object:
return std::hash<uint64_t>{}(my_val_);
It does the same thing as your second approach.
I can't tell for sure what _Do_hash does, but in any case it is non-standard and should not be used, to avoid portability issues.
Since a google search didn't turn up any documentation of the function, I would assume that it is an implementation detail of the standard library implementation that you are using and that isn't meant to be used by user code. Therefore you shouldn't use it at all, even if you don't care about portability.
Also note that it doesn't matter for performance whether you use your approach with a named variable or my approach using a temporary. The compiler will almost surely generate identical code from it. Which you use is purely a matter of code style.

What are the consequences of having a static pointer to this

I have a class that contains functions that need to run as threads. The proper way to do this (form what I understand) is have these functions declared as static. To use methods from this class I need a to have an instance to that class, so I create a static variable that is initialized to self in the constructor. What are the implications in efficiency and program logic?
class Foo
{
private: Foo* this_instance;
Foo()
{
this_instance=this;
}
void FooBar()
{
...
}
static void* Bar()
{
if (this_instance==NULL) return 1; //throws are not catched are they?
this_instance->FooBar();
return 0;
}
}
Not actual code but to make my question clearer.
The application actually works and I checked it with helgrind/memcheck and the errors are not related to the issue at hand. I'm asking this question because all solutions seem like workarounds, including this one. Others are like the one mentioned by doctor love, other using helper static method.
I am wondering if my approach would result in epic failures at some point in time, for some reason unknown to me and obvious to other more experienced programmers.
You do not need functions to be static to use them in threads. You could bind instance functions or pass the this pointer, or use C++11 with a lambda.
If you use raw threads you will have to catch exceptions in the thread - they will not propagate to the code that started the thread.
In C++11 you can propagate the exceptions, using current_exception and rethrow_exception. See here
EDIT
If you have a static pointer for each type, you can only have one instance of it, yet your code does nothing to prevent the static pointer being reset. Why bother having a class instance in the first place - surely just pass in the parameters? I think it's cleaner to have free functions to do the work. If you think it's not worth the effort, it's your code. What do your co-workers think of your design?

What do I name this class whose sole purpose is to report failure?

In our system, we have a number of classes whose construction must happen asynchronously. We wrap the construction process in another class that derives from an IConstructor class:
class IConstructor {
public:
virtual void Update() = 0;
virtual Status GetStatus() = 0;
virtual int GetLastError() = 0;
};
There's an issue with the design of the current system - the functions that create the IConstructor-derived classes are often doing additional work which can also fail. At that point, instead of getting a constructor which can be queried for an error, a NULL pointer is returned.
Restructuring the code to avoid this is possible, but time-consuming. In the meantime, I decided to create a constructor class which we create and return in case of error, instead of a NULL pointer:
class FailedConstructor : public IConstructor
public:
virtual void Update() {}
virtual Status GetStatus() { return STATUS_ERROR; }
virtual int GetLastError() { return m_errorCode; }
private: int m_errorCode;
};
All of the above this the setup for a mundane question: what do I name the FailedConstructor class? In our current system, FailedConstructor would indicate "a class which constructs an instance of Failed", not "a class which represents a failed attempt to construct another class".
I feel like it should be named for one of the design patterns, like Proxy or Adapter, but I'm not sure which.
EDIT: I should make it clear that I'm looking for an answer that adheres to, ideally, one of the GoF design patterns, or some other well-established naming convention for things of this nature.
To answer your literal question, I'd probably go with ConstructorFailure, as it describes the event of failing.
However, I'd probably go one step further and make it an Exception, in which case ConstructorException doesn't sound too shabby. Any reason you want to return this instead of throwing it?
I'd name it NullConstructor in line with the null object pattern, which is the pattern you're using. See http://en.wikipedia.org/wiki/Null_Object_pattern
Throw an exception. That is If I understand your description correctly and the creation of the IConstructor object is not done asynchronously.
Though if you don't have exceptions available to you I would probably call it ConstructorCreationError. Yes it does convey a failure mode but, more accurately, it is communicating the specific error that occurred. Also, having constructor as the last word, to me, seems to give the wrong meaning, but you could put "constructor" at the end as well.
You could also replace the verb "Creation" with something like SpawnConstructorError, ConstructorGenerationError and or if you're a fan of Dr. Chevalier maybe ErroneousConstructor.
I'd go for DummyConstructor because its only purpose is to simulate a valid Constructor instance, but no real functionality is implemented by it.
FailureResponseConstructor?
You're not creating a failure, you're creating the response to the failure. Thus, I would think any synonym to 'response' or 'respond' would work.
If you willing to spend effort checking returned pointer against the "FailureConstructor", I don't see reason why couldn't you check it against NULL ?
Unless your system is designed to mask component failure from each other, it just doesn't make sense to assume every associated parts are working well.
I'm going to go with something based on Niall C.'s comment -- FailedConstructorProxy. The Proxy pattern seems to fit best with what this class is; though rather than it relaying method calls to an object, it's standing in and generating what we wanted the actual constructor to return.
(If someone has a more correct answer, post it and I'll mark that one as accepted. I'm still not 100% convinced this is the right name!)
Why not create a Failed class to represent a class that failed construction and go with FailedConstructor? This way the naming is consistent.
I would suggest calling this class FailedObjectConstructionHandler which describes what the class does.

C++ static initialization order

When I use static variables in C++, I often end up wanting to initialize one variable passing another to its constructor. In other words, I want to create static instances that depend on each other.
Within a single .cpp or .h file this is not a problem: the instances will be created in the order they are declared. However, when you want to initialize a static instance with an instance in another compilation unit, the order seems impossible to specify. The result is that, depending on the weather, it can happen that the instance that depends on another is constructed, and only afterwards the other instance is constructed. The result is that the first instance is initialized incorrectly.
Does anyone know how to ensure that static objects are created in the correct order? I have searched a long time for a solution, trying all of them (including the Schwarz Counter solution), but I begin to doubt there is one that really works.
One possibility is the trick with the static function member:
Type& globalObject()
{
static Type theOneAndOnlyInstance;
return theOneAndOnlyInstance;
}
Indeed, this does work. Regrettably, you have to write globalObject().MemberFunction(), instead of globalObject.MemberFunction(), resulting in somewhat confusing and inelegant client code.
Update: Thank you for your reactions. Regrettably, it indeed seems like I have answered my own question. I guess I'll have to learn to live with it...
You have answered your own question. Static initialization order is undefined, and the most elegant way around it (while still doing static initialization i.e. not refactoring it away completely) is to wrap the initialization in a function.
Read the C++ FAQ items starting from https://isocpp.org/wiki/faq/ctors#static-init-order
Maybe you should reconsider whether you need so many global static variables. While they can sometimes be useful, often it's much simpler to refactor them to a smaller local scope, especially if you find that some static variables depend on others.
But you're right, there's no way to ensure a particular order of initialization, and so if your heart is set on it, keeping the initialization in a function, like you mentioned, is probably the simplest way.
Most compilers (linkers) actually do support a (non-portable) way of specifying the order. For example, with visual studio you can use the init_seg pragma to arrange the initialization into several different groups. AFAIK there is no way to guarantee order WITHIN each group. Since this is non-portable you may want to consider if you can fix your design to not require it, but the option is out there.
Indeed, this does work. Regrettably, you have to write globalObject().MemberFunction(), instead of globalObject.MemberFunction(), resulting in somewhat confusing and inelegant client code.
But the most important thing is that it works, and that it is failure proof, ie. it is not easy to bypass the correct usage.
Program correctness should be your first priority. Also, IMHO, the () above is purely stylistic - ie. completely unimportant.
Depending on your platform, be careful of too much dynamic initialization. There is a relatively small amount of clean up that can take place for dynamic initializers (see here). You can solve this problem using a global object container that contains members different global objects. You therefore have:
Globals & getGlobals ()
{
static Globals cache;
return cache;
}
There is only one call to ~Globals() in order to clean up for all global objects in your program. In order to access a global you still have something like:
getGlobals().configuration.memberFunction ();
If you really wanted you could wrap this in a macro to save a tiny bit of typing using a macro:
#define GLOBAL(X) getGlobals().#X
GLOBAL(object).memberFunction ();
Although, this is just syntactic sugar on your initial solution.
dispite the age of this thread, I would like to propose the solution I've found.
As many have pointed out before of me, C++ doesn't provide any mechanism for static initialization ordering. What I propose is to encapsule each static member inside a static method of the class that in turn initialize the member and provide an access in an object-oriented fashion.
Let me give you an example, supposing we want to define the class named "Math" which, among the other members, contains "PI":
class Math {
public:
static const float Pi() {
static const float s_PI = 3.14f;
return s_PI;
}
}
s_PI will be initialized the first time Pi() method is invoked (in GCC). Be aware: the local objects with static storage have an implementation dependent lifecyle, for further detail check 6.7.4 in 2.
Static keyword, C++ Standard
Wrapping the static in a method will fix the order problem, but it isn't thread safe as others have pointed out but you can do this to also make it thread if that is a concern.
// File scope static pointer is thread safe and is initialized first.
static Type * theOneAndOnlyInstance = 0;
Type& globalObject()
{
if(theOneAndOnlyInstance == 0)
{
// Put mutex lock here for thread safety
theOneAndOnlyInstance = new Type();
}
return *theOneAndOnlyInstance;
}