unique_ptr as general purpose dispose object - c++

Suppose I have a situation, where I have an SDK which provides certain interface, which implies some manual resources management or state changes. It is supposed to be used like this:
// SDK has state B by default
SDK->setStateA();
something();
requiring();
stateA();
SDK->setStateB();
Is it a good idea to incapsulate state changes as custom allocator/deleter for unique_ptr object or, probably, it would be better to get this behaviour through some manual Dispose pattern implementation.
Since it's not a resource allocation, I have doubts. It might cause confusion and make code cryptic.
My other concern is that I need a return code from both init and clean up steps. I could use lambdas and get those through captures, but it looks even more cryptic.
Maybe someone tried it already and saw how it makes code look after a while?

Generally, it is best to design the interface of the code in such a way that it is easy to use and intuitive, or, put differently, that it's hard to use it wrongly. In particular, if the interface is able to prevent bugs by refusing compilation, it can save a lot of debugging time.
One possibility to achieve such an interface would be something that can be loosely related to the std::mutex <---> std::unique_lock mechanics:
class state_guard {
std::unique_ptr<SDK_type>& SDK;
state_guard(std::unique_ptr<SDK_type>& s) : SDK{ s } {
SDK->setStateA();
}
~state_guard() {
SDK->setStateB();
}
};
void something(state_guard&, ...);
void requiring(state_guard&, ...);
void stateA(state_guard&, ...);
std::unique_ptr<SDK_type> SDK{ get_sdk() };
{
state_guard guard{ SDK };
something(guard, ...);
requiring(guard, ...);
stateA(guard, ...);
}
By forcing to pass the guard as a function argument (even if it is unused in the respective function), the user cannot forget to set to stateA (and thanks to RAII, to reset it to stateB).

Related

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?

C++ logging wrapper design

I would like to add a log to my application. I've picked a logging library but I'd like to be able to switch to a different library without having to alter any code that uses logging.
Therefore, I need some sort of logging wrapper that is flexible enough to utilize pretty much any underlying logging library's functionality.
Any suggestions for such a wrapper's design?
EDIT: one feature I must have in this wrapper is component tagging. I want my algorithm class to have "X:" appear ahead of its log lines, and my manager class to have "Y:" appear. How to propagate this these tags onto the underling log and how to build the component tag naming mechanism is one major design question here.
Your best bet is to make the interface as simple as possible. Completely separate the logging user's interface from how the logging actually gets implemented.
Cross-cutting concerns always are expensive to maintain, so making things any more complicated will make you hate life.
Some library only wants something simple like this:
void logDebug(const std::string &msg);
void logWarning(const std::string &msg);
void logError(const std::string &msg);
They shouldn't add or specify any more context. No one can use the information anyway, so don't over design it.
If you start adding more information to your logging calls it makes it harder to reuse the client code that uses it. Usually you will see this surface when components are used at different levels of abstraction. Especially when some low level code is providing debug information that is only relevant to higher levels.
This doesn't force your logging implementation (or even the interface the logging implementation conforms to!) into anything either, so you can change it whenever.
UPDATE:
Insofar as the tagging, that is a high level concern. I'm going to speculate that it doesn't belong in the log, but that is neither here nor there.
Keep it out of the logging message specification. Low level code shouldn't give a flying truck who you or your manager is.
I don't know how you specify X or Y in your example. How you do that isn't really obvious from the description we are given. I'm going to just use a string for demonstration, but you should replace it with something type safe if at all possible.
If this is always on, then just having an instance context (probably a global variable) might be appropriate. When you log in, set the context and forget about it. If it ever isn't set, throw with extreme prejudice. If you can't throw when it isn't set, then it isn't always on.
void setLoggingContext("X:");
If this changes at different levels of abstraction, I would consider a stack based RAII implementation.
LoggingTag tag("X:");
I'm not sure what your requirements are in the scenario when different stack frames pass in different values. I could see where either the top or the bottom of the stack would be reasonable for differing use cases.
void foo() {
LoggingTag tag("X:");
logWarning("foo");
bar();
baz();
}
void bar() {
LoggingTag tag("Y:");
logWarning("bar");
baz();
}
void baz() {
logWarning("baz");
}
Either way this shouldn't affect how you add a message to the log. The baz function doesn't have the context to specify the LoggingTag. It's very important that using logWarning doesn't know about tags for this reason.
If you wanted to tag based on some type, you could do something simple like this.
struct LoggingTag {
LoggingTag(const std::string &tag_) : tag(tag_) {}
template<typename T>
static LoggingTag ByType() {
return LoggingTag(typeid(T).name());
}
std::string tag;
};
void foo() {
LoggingTag tag = LogginTag::ByType<int>();
}
This wouldn't force someone to use typeid(T).name() if they didn't want to, but gave you the convenience.
I like this approach:
class Log {
public:
virtual logString(const std::string&)=0;
};
template <typename T>
Log& operator<<(Log& logger, const T& object) {
std::stringstream converter;
converter << object;
logger.logString(converter.str());
return logger;
}
Simple and quick! All you need to do is reimplement the logString method...
Take a look at zf_log library. It is very small (~2000k lines, ~10KB when compiled) and fast (see comparison table in README.md). It is very close to what you describe as wrapper. It gives you an abstract API that you can use in your project and allows to specify what actual logging implementation to use. See custom_output.c example where syslog is used as output facility. It also could be used privately inside libraries without risk of getting into conflict with other code that could use this library (see ZF_LOG_LIBRARY_PREFIX define for more info).
Even if it's not exactly what you are looking for, I guess it could be a good example for your wrapper thing.

Redundant code in exception handling

I've a recurrent problem, I don't find an elegant solution to avoid the resource cleaning code duplication:
resource allocation:
try {
f()
} catch (...) {
resource cleaning code;
throw;
}
resource cleaning code;
return rc;
So, I know I can do a temporary class with cleaning up destructor, but I don't really like it because it breaks the code flow and I need to give the class the reference to the all stack vars to cleanup, the same problem with a function, and I don't figure out how does not exists an elegant solution to this recurring problem.
This problem is why RAII was invented. The best practice is to make sure that every releasable resource is inside an object. Alternately, you can use Boost.ScopeExit or define a generic sentinel class (a class that receives a functor in constructor and calls it in the destructor)
Edit: In the article pointed out by #Jackson, this is called ScopeGuard. The implementation in the article could greatly enhanced by combining it with boost::function and boost::bind - or std::tr1::function and std::tr1::bind).
Basically instead of the whole architecture in the article, your implementation would look like this:
class scoped_guard
{
boost::function<void(void)> atScopeExit;
public:
scoped_guard(const boost::function<void(void)>& func) : atScopeExit(func) {}
~scoped_guard() { try { atScopeExit(); } catch(...) {} }
};
You can further enhance this by adding the capability to dismiss it or other things (capturing exceptions safely in case of stack unwinding?) but
I'm too lazy to that's left as an exercise to the reader ;).
You might want to have a look at boost::scope_exit:
http://www.boost.org/doc/libs/1_39_0/libs/scope_exit/doc/html/index.html
This Dr Dobbs article might help.
You need self-releasing resources, which is really not hard to do.
For memory use autopointers, STL, Boost or make your own, it isn't hard.
For files, preferably use an std::fstream. If you must use fopen or CreateFile (or whatever) make a simple handle class that calls the appropriate close function on destruction.
Similarly for any other resources, build a collection of smart handle classes.

Advice on wrapping third party libraries

I have been working a year now as a software developer for a at the computer-vision department of a company. My main job is integration of third-party software into a framework, so i usually end up writing wrapper libraries because a lot of this third party software does not work the way we want it to work(not thread safe, pain in the a** to use etc.).
Normally i just wrap the whole library and guard the calls to the library with mutual exclusions(thread safety is somehow the major problem with most extern libraries). I really enjoy doing this, as it puts you into a lot of interesting situations and you get to see a lot of interesting code. However i often think that i am not doing it properly or that my implementation is not really good. I feel like i am lacking some sort of design knowledge on how to properly do stuff like that.
Basically i want to know if there are any good guidelines or hints about designing a proper 'API ontop of broken API', or if this is always bound to be quite hackish and ugly.
I will quote an answer to another question on here the other day:
Does your current method pass testing?
Is it fast enough?
If yes, keep doing what you are doing.
As an alternative
Just ensure your new API encompasses both the intended functionality and the conventional or accidental functionality of the original. Also ensure it presents a 'fit-for-purpose' re-presentation. Take a peek at the C++ wrapping of C libraries in FOSS projects such as GTK/GTK for C++ (which just wraps the former).
If the API is broken, fix it and submit a patch ... get involved with the third-parties (I am assuming having access to the source means they won't mind this) ... You could re-write some of their API to be 'wrapping friendly' and suggest they merge some changes. If there is a problem, be the one to fix it.
Not much to it, just wrap A with B and ensure B does what A was supposed to, or is used for.
The only thing that I can add to Aiden's response is that you should also look to replace code that requires explicit initialization and termination with RAII techniques. When I've been faced with providing a façade over APIs, I always seem to run into a class that looks like:
struct ADVERTISER {
/* a bunch of members here */
};
void adv_Initialize(ADVERTISER *adv, /* a bunch of arguments */);
void adv_DoStuff(ADVERTISER *adv);
void adv_Terminate(ADVERTISER *adv);
I've seen this wrapped in a C++ class in the following manner:
namespace wrapper {
class Advertiser {
public:
Advertiser(): inited_(false) {}
void initialize(/* a bunch of arguments */) {
terminate();
adv_Initialize(&adv_, ...);
inited_ = true;
}
void doStuff() {
validate();
adv_DoStuff(&adv_);
}
void terminate() {
if (inited_) {
adv_Terminate(&adv_);
inited_ = false;
}
}
protected:
void validate() {
if (!inited_) {
throw std::runtime_error("instance is not valid");
}
}
private:
ADVERTISER adv_;
bool inited_;
};
}
The problem is that the Advertiser class doesn't really make the API any easier to use or even cleaner IMHO. If you run into cases like this, then:
Use a fully parameterized constructor to ensure that invalid instances do not exist
Clean up all resources in the destructor
Write a copy constructor and assignment operator if they make sense or make them private and don't implement them.
My goal is to make sure that whatever API I am presenting/creating/wrapping works with our existing coding style. I also try to bend the API into a more OO style than it may currently be in. I have seen a number of what I call object-oriented C like the one that I presented above. If you want to make them really fit into C++, then make then truly object-oriented and take advantage of what C++ gives you:
Be careful to manage any state variables.
If actions like copying don't make sense, then hide them.
If there is any possibility of leaking resources, then find some way to prevent it from happening (usually employing RAII helps).
Restrict the creation of instances using constructors to eliminate invalid instances and other edge cases.

Good or Bad C++ Idiom - Objects used purely for constructor/destructor?

I have a few classes which do nothing except in their constructors/destructors. Here's an example
class BusyCursor
{
private:
Cursor oldCursor_;
public:
BusyCursor()
{
oldCursor_ = CurrentCursor();
SetCursor(BUSY_CURSOR);
}
~BusyCursor()
{
SetCursor(oldCursor_);
}
}
// example of use
void DoSlowThing
{
BusyCursor busy;
... do something time-consuming ...
}
I'm a little concerned about future readability. Am I being too "tricksy" here, with a variable ("busy") which is never actually used in the code? Could some static analysis tool suggest they be removed, or is this idiom sufficiently common not to worry about?
This technique is very common and is known as the design pattern: Resource Acquisition Is Initialization (RAII).
I would not hesitate to use this design pattern at all.
It's much better that you are coding using this design pattern because you will avoid bugs by forgetting to reset the cursor, or whatever the resource in question is.
If you are concerned that other programmers might not understand it, then those programmers should be more educated. Always strive to code in the most error free way where you make it impossible for you and others to shoot yourself/themselves in the foot.
"Could some static analysis tool suggest they be removed?"
No static analysis tool will see this as a problem.
No compiler warning will be given
No compiler optimization will cause any problems.
The reason is because the object is created and the constructor/destructor are called. So it is not an unreferenced variable.
As others have said, this is good C++ style. To aid readability, I always prefix such RAII-only classes with Scoped (for example, ScopedBusyCursor) to make it clear from a glance what the class's purpose is.
This a well-known and good C++ idiom, like the others answered.
To make it clear that the classes are meant to be only used within a scope and not to be moved between different scopes, it might be good to make them noncopyable. This can be done manually by adding an unimplemented private copy-constructor and copy-assignment operator. The shorter and more readable way is to derive the class from boost::noncopyable:
#include <boost/noncopyable.hpp>
class BusyCursor : public boost::noncopyable // for scoped use only
{
// ...
};
It's a good idiom and commonly used.
It's better than any alternative, for example even if your something time-consuming code throws an exception, the ~BusyCursor destructor will still be called.
Arguably not using this pattern is the bad idiom. When you are not using RAII your code ends up looking like this:
void func() {
Cursor oldCursor = CurrentCursor();
SetCursor(BUSY_CURSOR);
try {
do_slow_stuff();
SetCursor(oldCursor);
} catch (...) {
SetCursor(oldCursor);
throw;
}
}
Do you really think having that littered throughout your code is better for maintenance?
No sane static analysis tool would suggest removing the variable, becaues it is used. It has an effect because its constructor and destructor are called. You should be perfectly safe.
Others have already mentioned that this is classic RAII.
What I'll add is to say that this is one of the best things about C++. Very few other languages support it, or at least support it properly (even C#'s using construct isn't as good, as the burden is still on the client code - see my blog entry on this).
It's become so closely associated with C++ that you should feel confident that anyone reading it would be familiar with it - and if not they should be.
I usually refer to this as a "guard". In my opinion it demonstrates one of C++'s biggest strengths (deterministic resource-handling). It's one of the things I miss the most when working in garbage-collected languages.
You can also go with something like ScopeGuard by Andrei Alexandrescu and Petru Marginean. Your sample would look something like this then:
void DoSlowThing
{
Cursor oldCursor = CurrentCursor();
SetCursor(BUSY_CURSOR);
ON_BLOCK_EXIT(SetCursor, oldCursor);
... do something time-consuming ...
}
This makes it easier to do one-off RAII-type operations without having to create a new class for each one. However for your Cursor example, since it's a class you'll likely reuse many times, you're probably better off with the dedicated class.