Long lived objects - c++

I have a class that provides a utility for logging errors and exceptions. This is part of a library that's integrated into other applications. This class is implemented via the Singleton pattern (Meyer's singleton to be specific). The issue arises during the destruction phase when there's no defined point in time when this class is destructed. It so happens that during destruction an error/exception is raised which tries to access this class and leads to undefined behavior. Any flag within the class to maintain its state seemed moot since accessing the flag itself is UB once the object is destructed. I can only think of having the object allocated on the heap and letting it linger till the program execution but an issue with that is instruments designed to detect memory leaks would report this. I've also tried installing an std::atexit() handler but that too was invoked before the destruction of the object which doesn't help. How are such issues of lifetime best handled?
EDIT: Here's a short snippet to illustrate the problem
#include <iostream>
#include <memory>
#define LOG_EXCEPTION(msg) Logger::instance()->logException(msg)
#define LOG_MESSAGE(msg) Logger::instance()->logMessage(msg)
struct Logger {
Logger() = default;
~Logger() {
std::cout<<"~Logger\n";
}
int x;
public:
static const std::shared_ptr<Logger>& instance() {
static auto logger = std::make_shared<Logger>();
return logger;
}
void logException(std::string const& msg) {
++x;
std::cout<<msg<<'\n';
}
void logMessage(std::string const& msg) {
++x;
std::cout<<msg<<'\n';
}
};
struct Foo {
~Foo() {
//Something wrong, so log an exception
LOG_EXCEPTION("oops");
}
};
int main()
{
static Foo f;
LOG_MESSAGE("message"); // Just to force creation of the Logger object
}
As is evident, since Foo f outlives the singleton instance, it is UB to access the Logger instance from its destructor. This is just a demonstrative code but such logging of exceptions can happen at any point in the program sequence and it's difficult to reason about the ordering of the statics (the actual error isn't even from a static instance).

In an overly simplified way that would depend on your code not having other singletons or globals that use in their destructors this Logger you could just:
int main()
{
LOG_MESSAGE("start message"); // Just to force creation of the Logger object
{
static Foo f;
//All the rest of your code here.
}//Everything else is destroyed here.
//This could be a function instead of a block.
}//Logger is destroyed here
But if the preconditions are not met (other globals/singletons) then moving away from the Meyers Singleton will be necessary. A "reviving" singleton or dependency injection as suggested in the comments would be good possibilities.

Related

What is ScopeGuard in C++?

I am under the impression that it is a C++ class contained in a library written by a third party. I tried searching on Google, and I found one post that said it was a good idea to use it. However, it failed to describe exactly what it is and how I can incorporate it into my code. Thanks.
ScopeGuard was once a particular implementation of scope guards by Petru Marginean and Andrei Alexandrescu. The idea is to let the destructor of a guard object call a user specified cleanup action at the end of a scope (read: block), unless the scope guard is dismissed. Marginean came up with an ingenious idea of declaring a scope guard object for C++03, based on lifetime extension of a reference to const.
Today “scope guard” is more the general idea.
Scope guards are based on RAII (automatic destructor calls used for cleanup), just as e.g. a for loop is based on jumps, but one wouldn't ordinarly call a for loop a jump-based piece of code, because that loses most of the information of what it is about, and likewise one does not ordinarily refer to scope guards as RAII. for loops are at a higher level of abstraction, and are a more specialized concept, than jumps. Scope guards are at a higher level of abstraction, and are a more specialized concept, than RAII.
In C++11 scope guards can be trivially implemented in terms of std::function, with the cleanup action supplied in each place via a lambda expression.
Example:
#include <functional> // std::function
#include <utility> // std::move
namespace my {
using std::function;
using std::move;
class Non_copyable
{
private:
auto operator=( Non_copyable const& ) -> Non_copyable& = delete;
Non_copyable( Non_copyable const& ) = delete;
public:
auto operator=( Non_copyable&& ) -> Non_copyable& = default;
Non_copyable() = default;
Non_copyable( Non_copyable&& ) = default;
};
class Scope_guard
: public Non_copyable
{
private:
function<void()> cleanup_;
public:
friend
void dismiss( Scope_guard& g ) { g.cleanup_ = []{}; }
~Scope_guard() { cleanup_(); }
template< class Func >
Scope_guard( Func const& cleanup )
: cleanup_( cleanup )
{}
Scope_guard( Scope_guard&& other )
: cleanup_( move( other.cleanup_ ) )
{ dismiss( other ); }
};
} // namespace my
#include <iostream>
void foo() {}
auto main() -> int
{
using namespace std;
my::Scope_guard const final_action = []{ wclog << "Finished! (Exit from main.)\n"; };
wcout << "The answer is probably " << 6*7 << ".\n";
}
The rôle of the function here is to avoid templating so that Scope_guard instances can be declared as such, and passed around. An alternative, slightly more complex and with slightly constrained usage, but possibly marginally more efficient, is to have a class templated on a functor type, and use C++11 auto for declarations, with the scope guard instance created by a factory function. Both these techniques are simple C++11 ways to do what Marginean did with reference lifetime extension for C++03.
It's more of a design pattern than a particular class. It is a way of aquiring/releasing resources (such as files, memory, or mutexes) that is exception safe. unique_lock in c++11 follows this pattern.
For example, with unique_lock, instead of writing code like this:
void foo()
{
myMutex.lock();
bar();
myMutex.unlock();
}
You write code like this:
void foo()
{
unique_lock<mutex> ulock(myMutex);
bar();
}
In the first case, what if bar throws an exception? Then, myMutex will never be unlocked, and your program would be left in an invalid state. In the second case, however, unique_lock is programmed to lock the mutex in its constructor, and unlock it in its destructor. Even if bar throws an exception, the unique_lock will be destructed as the stack unwinds when the exception travels upward, and so the lock will be released. This saves you having to wrap every call to bar in a try/catch block and handle exceptions manually.

Design a class/type with only 1 possible instance - C++

I would like to have a class T that can generate only 1 instance in the whole program.
Now i know about std::unique_ptr but there are 2 problems:
it's limited to a scope ( but it's not a big issue ... )
it needs to be explicitly used, meaning that it's not part of the class or the type, it's just and handler and a special pointer, but it does not modify the design of my class.
now i would like to have class T designed in a way that not even by mistake the user can declare 2 instances in the same program and i can't rely on the fact that my user will declare an std::unique_ptr for T because i want to solve this by design.
right now i'm only thinking about how to make an implicit use of an unique_ptr in an elegant way, the problem is that i do not have any clue at the moment.
the other way around is to check if this class is handled by an unique_ptr but this check will make me lose an edge in terms of performances.
since having only 1 instance is really important, i see only 2 options in my case: 1) trying to solve this by design 2) throwing errors at compile time with some sort of check/macro.
I know that this looks trivial but with a design approach it's not, at least for me, so please help.
What you're looking for is called the Singleton pattern, and while it is widely considered by many (myself included) to be an anti-pattern, I will nonetheless show you the basic elements needed to build one.
Basically what you need to do is provide three things:
A static method which "gets" the one and only instance
A private constructor, so that nobody can ever instantiate it
(optional) A means by which the one and only instance is created before main starts
Here's the essential code:
class Singleton
{
public:
Singleton& get()
{
static Singleton me_;
return me_;
}
private:
Singleton() {};
};
I leave it to you to discover how to implement #3 above, and why you shouldn't be using a Singleton in the first place -- there are many reasons.
This is typically referred to as a Singleton.
See http://en.wikipedia.org/wiki/Singleton_pattern
The typical trick in C++ is to have a function which returns the singleton instance by reference, and make the constructor private.
Something like:
#include <iostream>
using namespace std;
class Foo
{
private:
Foo() : a(3) { a++; }
static Foo singleton;
int a;
public:
static Foo& getFoo() { return singleton; }
void doStuff() { cout<<"My a is: "<<a<<endl; }
};
Foo Foo::singleton;
int main(int argc, char** argv)
{
Foo::getFoo().doStuff();
Foo &foo = Foo::getFoo();
foo.doStuff();
//uncomment below to cause compile error
//Foo foo2;
}
Note that in real code you'll split this up into a header and a cpp file. In that case the
Foo Foo::singleton;
part must go in the cpp file.
You could have at least
static int count;
assert(count == 0);
count++;
in the constructor(s) of the singleton class. This don't ensure at compile time that your class is singleton, but at least it checks that at runtime.
And you could also make the constructor private, and have a static member function returning (once) a pointer to your instance, perhaps something like
class Singleton {
private:
Singleton() {
static int count;
assert(count == 0);
count++;
};
Singleton(Singleton&) = delete;
public:
static Singleton* the_instance() {
static Singleton* it;
if (!it) it = new Singleton();
return it;
}
};

Callback into singleton class

I am using a singleton class with a thread that calls into the singleton. I was asked during a review why I used the this pointer instead of the singleton instance.
My code with the suggested changes.
class myClass : public threadWrapper
{
public:
static myClass& instance()
{
static myClass instance;
return instance;
}
// This is the callback that I have implemented
static void callback(void *me)
{
if (me != NULL)
static_cast<myClass*>(me)->doCallback();
}
// This is the suggested callback
static void callback2(void *me)
{
instance().doCallback();
}
// caller gets instance and then calls initialise()
int initialise()
{
if (initialised)
return ERROR_ALREADY_INITIALISED;
// Initialise the class
// my thread startup call
// thread wrapper class initialisation that calls pthread_create that runs the callback method with this as a parameter
// priority is a global value that difines the relative priority of the various threads.
threadWrapper::Initialise(priority, callback, this);
initialised = true;
}
private:
myClass() : initialised(false) {;}
void doCallback(void);
bool initialised;
static const int
}
So is there any significant difference in speed between the two?
The threadWrapper is mandated in the existing code base, and I'm not allowed to use boost.
My justification was that if we needed to make this not a singleton then fewer changes would be required.
The speed difference will be pretty much nonexistent.
As for code quality, Singletons are quite horrendous and I personally would chuck out both forms, especially in a threaded environment. Assuming that it's too late for that, however.
The thing is, if you're gonna pass in a pointer to the object, why not just not make that object global in the first place? And if you are, it should at least be strongly typed. And then, you're just ... wrapping a member method in a static method? Why bother? Anyone who has a pointer to the class can just call the method on it in the first place. This is just insane.
Edit: If you're stuck with the existing design, then the second version is definitely better than the first and no slower. Even if you have existing code that depends on the Singleton, then it's absolutely better to refactor what you can to not depend on it.

C++ Controlling destructor order for global objects

I've got a class (A) that accesses (indirectly via a static method) a static variable (an STL container) in another class (B) in its constructor and destructor.
A objects may be global, global constants, static members of another class, stored in other classes (which may themselves have global or static instances) or basically anywhere else a c++ object can be.
If an A object is constructed before the static members in B or destructed after the static members in B, it will cause a crash at some point (usually an access violation).
Is there some way to guarantee that all instances of class A (except those that have leaked, since by definition there "lost" and so wont be destructed any way) are constructed after and destructed before B's static variable?
I've seen some solutions for making a specific variable be constructed/destructed before/after another, however not a general case of all instances of a given type so am not sure how to approach this.
No. This is known as the static-initialization fiasco. The order that objects get constructed prior to entering main is unspecified. The only guarantee is that it happens.
What you can do is lazy-initialize. This means your objects won't be initialized until you use them. Such as:
struct A { /* some data */ };
struct B { B(void){ /* get A's data */ } };
A& get_A(void)
{
static A instance;
return instance;
}
B& get_B(void)
{
static B instance;
return instance;
}
You use get_A and get_B to get the global instances. The part where B uses A should use get_A, and your use of B should be with get_B. Note the get_B is optional in your case.
What happens when B is first created? (Either globally or in the function) The constructor will call get_A and that's where A will be created. This let's you control the order things get constructed.
Note I think I reversed your A and B.
In general, no such method. There are workarounds, though. You can get an object with global scope and a slightly-less-than global lifetime by having a global pointer and initializing/destructing it in main/WinMain. Also, you place your global state to be destructed last in a ref-counted heap object.
Also, consider redesign :)
The book "Modern C++ Design" covers this issue nicely.
Google Books contains scans of much of it - see section 6.5 (page 135) - link.
You can handle this cleanly, by putting pointers to the objects in global space,
then newing them in the desired order in your main, and destroying them in the desired order at the end of the main.
As others pointed, there is no standard and portable way to solve this problem, due to the Static initialization order fiasco issue.
However, you should be able to solve your problem by applying a bit of design, so you gain a degree of control when (and how) objects of A and B are constructed. Take a look on design patterns like creational pattern Singleton it is considered in many (if not most) cases as anti-pattern, despite it is worth to learn about it. Also look at to Monostate pattern which may be used as a bit better Singleton. These patterns can help to control object creation and lifetime, so things are properly initialized before use.
Generally, it's a good idea to avoid globals - sticking to deglobalisation is a good idea.
In case if you use lazy singletons (that return on-demand created statics) you may end up with possibility where one singleton uses another one after it was already deleted. For example, imagine you have a global HttpClient singleton that allows you to make http requests. Also, you probably want to have logging, which might be provided by Log singleton:
class HttpClient
{
...
static HttpClient& singleton()
{
static HttpClient http;
return http;
}
};
Same for Log singleton. Now, imagine HttpClient constructor and destructor simply log that that HttpClient was created and deleted. In this case destructor of HttpClient may end up using deleted Log singleton.
Sample code:
#include <stdio.h>
class Log
{
Log()
{
msg("Log");
}
~Log()
{
msg("~Log");
}
public:
static Log& singleton()
{
static Log log;
return log;
}
void msg(const char* str)
{
puts(str);
}
};
class HttpClient
{
HttpClient()
{
Log::singleton().msg("HttpClient");
}
~HttpClient()
{
Log::singleton().msg("~HttpClient");
}
public:
static HttpClient& singleton()
{
static HttpClient http;
return http;
}
void request()
{
Log::singleton().msg("HttpClient::request");
}
};
int main()
{
HttpClient::singleton().request();
}
and the output is:
Log
HttpClient
HttpClient::request
~HttpClient
~Log
So far everything is correct, simply because it happened that Log was constructed before HttpClient, which means that HttpClient can still use Log in its destructor. Now simply comment out logging code in HttpClient constructor and you'll end up with this output:
Log
HttpClient::request
~Log
~HttpClient
As you can see, log is being used after its destructor ~Log was already called. As pointed out, deglobalization might be a better approach, but if you want to use on-demand created singletons and make some of them live longer than the others, then you can make such singletons use a global static initialized on demand. I use that approach quite often in production code:
class Log
{
friend std::unique_ptr<Log>::deleter_type;
...
static std::unique_ptr<Log> log;
static Log& createSingleton()
{
assert(!log);
log.reset(new Log);
return *log;
}
public:
static Log& singleton()
{
static Log& log = createSingleton();
return log;
}
};
std::unique_ptr<Log> Log::log;
Now, regardless of order in which these singletons were constructed, destruction order will ensure that Log is destructed after HttpClient. This, however, might still fail and produce unexpected output if HttpClient was used from a global static constructor. Or if you want to have multiple such "super" globals (like Log and Config for example) that use each other in random order, you will still have these problem. In such cases sometimes it's just better allocate once on heap never delete some of these objects.

Common pattern for library initialization and shutdown?

Is there a pattern that I may use for calling the required initialization and cleanup routines of an underlying (C) library? In my case, I would like to create the wrapper class so that it can be composed into other objects. The problem is that, when I destroy the wrapper class, the cleanup routines of the underlying library are called. That's fine until I instantiate multiple objects of my wrapper class. My question is what is the best way to really handle this situation? A static reference counter comes to mind, but I wanted to know if there were other potentially better options and the trades involved.
If the initialization can be called before main starts, and cleanup called after main ends, this little trick (hack?) might work for you:
#include <iostream>
// C library initialization routine
void init() {std::cout << "init\n";}
// C library cleanup routine
void fini() {std::cout << "fini\n";}
// Put this in only one of your *.cpp files
namespace // anonymous
{
struct Cleaner
{
Cleaner() {init();}
~Cleaner() {fini();}
};
Cleaner cleaner;
};
int main()
{
std::cout << "using library\n";
}
Output:
init
using library
fini
It uses (abuses?) the fact that constructors for static objects are called before main, and that destructors are called after main. It's like RAII for the whole program.
Not everything has to be a class. The Singleton pattern would let you turn this into a class, but it's really not buying you anything over global functions:
bool my_library_init();
void my_library_shutdown();
The first call returns true if the library was successfully initialized, the second just quietly does whatever needs to be done and exits. You can add whatever reference counting or thread tracking type stuff behind these interfaces you like.
Also, don't neglect the possibility that your library may be able to do all of this transparently. When the first library function is called, could it detect that it is not initialized yet and set everything up before doing the work? For shutdown, just register the resources to be destroyed with a global object, so they are destroyed when the program exits. Doing it this way is certainly trickier, but may be worth the usability benefit to your library's callers.
I have seen a lot of Singleton talk, so I can only recommend a look at Alexandrescu's work.
However I am not sure that you really need a Singleton there. Because if you do, you assume that all your calls are going to share the state... is it the case ? Do you really wish when you call the library through a different instance of Wrapper to get the state in which the last call set it ?
If not, you need to serialize the access, and reinitialize the data each time.
class Wrapper
{
public:
Wrapper() { lock(Mutex()); do_init_c_library(); }
~Wrapper() { do_clean_up_c_library(); unlock(Mutex()); }
private:
static Mutex& Mutex() { static Mutex MMutex; return MMutex; }
}; // class Wrapper
Quite simple... though you need to make sure that Mutex is initialized correctly (once) and live until it's not needed any longer.
Boost offers facilities for the once issue, and since we use a stack based approach with MMutex it should not go awry... I think (hum).
If you can change the library implementation, you could have each call to one of the library's functions access a singleton which is created on first use.
Or you put a global/static variable into the library which initializes it during construction and shuts it down during destruction. (That might become annoying if the library uses global variables itself and the order of initialization/shutdown conflicts with them. Also, linkers might decide to eliminate unreferenced globals...)
Otherwise, I don't see how you want to avoid reference counting. (Note, however, that it has the drawback of possibly creating multiple init/shutdown cycles during the program's lifetime.)
If your set of C library routines is not too large, you can try combining the Singleton and Facade patterns so that C library routines are only invoked via the Facade. The Facade ensures the initialization and cleanup of the C library. Singleton insures that there is only one instance of the Facade.
#include <iostream>
// C library initialization and cleanup routines
void init() {std::cout << "init\n";}
void fini() {std::cout << "fini\n";}
// C library routines
void foo() {std::cout << "foo\n";}
void bar() {std::cout << "bar\n";}
class Facade // Singleton
{
public:
void foo() {::foo();}
void bar() {::bar();}
static Facade& instance() {static Facade instance; return instance;}
private:
Facade() {init();}
~Facade() {fini();}
};
// Shorthand for Facade::instance()
inline Facade& facade() {return Facade::instance();}
int main()
{
facade().foo();
facade().bar();
}
Output:
init
foo
bar
fini