Redundant code in exception handling - c++

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.

Related

unique_ptr as general purpose dispose object

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).

What is the meaning of a C++ Wrapper Class?

I have a little trouble in understanding a wrapper class. It would be great if some one could help providing apt examples.
What is a C++ Wrapper Class and what are the circumstances of writing it ?
What is it's use any way ?
Thanks.
A "wrapper class" is a de facto term meaning a class that "wraps around" a resource; i.e, that manages the resource. When people write a wrapper, then, they are doing something like this:
class int_ptr_wrapper
{
public:
int_ptr_wrapper(int value = 0) :
mInt(new int(value))
{}
// note! needs copy-constructor and copy-assignment operator!
~int_ptr_wrapper()
{
delete mInt;
}
private:
int* mInt;
};
This class manages ("wraps") a pointer to an int. All resources should be wrapped in some fashion, for cleanliness (no explicit clean up code or noise) and correctness (destructor is guaranteed to run; cannot forget to clean up, and safe with exceptions).
This pattern is called Scoped-bound Resource Management (SBRM), though a far more common (but most esoteric) name is Resource-Acquisition is Initialization (RAII). The idea is to bind a resource's clean-up to a destructor, for the reasons given above: the scope handles the rest.
Note that I said it was missing a copy-constructor and copy-assignment operator. This is due to the Rule of Three. (See linked question for detailed explanation.) The simplest way to correctly implement this rule is with the copy-and-swap idiom, explained here.
Sometimes, it's not pragmatic to write wrapper class for resource clean-up, usually when the resource is unique or used once. (Or with transactional programming.) The solution to this is called scope guard, a way of writing clean-up code inside the function that needs it.
You may find more information by searching for it in your favorite search provider (that is, Google), or going to the "primary" document here. Note that Boost provides a utility for this, as it usually does for good idioms.
A wrapper is just some smallish class whose purpose is to provide a different interface than the thing it wraps. For example, it is common to take a C API and write one or more classes that "wrap" it to provide an object-oriented interface rather than a procedural one.
You asked for circumstances of writing wrapper classes.For example, if you are in a company that makes use of different types of cameras, let us say USB, firewire etc. Each of the manufacturers will provide a different set of functions through an API to start the camera, set the parameters and read the image stream from it.
Now the programmer who builds the applications in your company need to be insulated from all the specific details in the various APIs. Now, what you can do is write a wrapper class around the APIs for each of the cameras or smarter, just one class with simple functions, wrapping around the existing code provided by the API.
For instance, we can design classes
MyUSBCameraWrapperClass,
MyFirewireCameraWrapperClass
with some member functions like
setFrameRate(int fps),
getImgFrame(*framebuffer), etc.
The programmers in your company can then use MyUSBCameraWrapperClass usbcam; usbcam.setFrameRate(30), etc. You get the point??
A wrapper class is a class that wraps a functionality with another interface.
Suppose you have the function f():
void f() { std::cout << "hello\n"; }
A simple wrapper class might be
class C {
f() { std::cout << "hello\n"; }
};
You might write a wrapper when your existing codebase expects a particular interface. This is the essence of the adapter design pattern. Or you might wrap a function in a class if you wish to maintain state for that function. Or you might wrap a function in a class' constructor or destructor if you want it to conveniently and automatically be called for you in a correct and deterministic manner. And the list goes on.
I use two kinds:
resource wrappers for function pairs provided by the OS like
UNIXs: open/close, mmap/munmap, dlopen/dlclose
Windows: CreateFile/DestroyHandle, CreateFileMapping/CloseHandle, LoadLibrary/FreeLibrary
functional wrappers for functions provided by the OS like
UNIXs: write, read, dlsym
Windows: ReadFile, WriteFile, GetProcAddress
The resource wrapper makes certain, that compiler generated code worries about the destruction of the resource created by the constructor via what is today called RAII. It is easy to combine such classes via base/member class relationships into complex classes.
In case of the creation function fails, a system error exception is thrown, providing rich error information about the error.
The functional wrapper is used instead of the plain OS function. Also in case of failure a system exception is being thrown.
This way somebody using my code doesn't need a debugger and debug code to find out what is failing in a complex environment with many libraries and processes and remote machines.
Also these wrappers provide some OS abstraction -- the code using them does not have to worry about OS differences.

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.

What's the proper "C++ way" to do global variables?

I have a main application class, which contains a logger, plus some general app configurations, etc.
Now I will display a lot of GUI windows and so on (that will use the logger and configs), and I don't want to pass the logger and configurations to every single constructor.
I have seen some variants, like declaring the main class extern everywhere, but that doesn't feel very object oriented. What is the "standard" C++ way to make elements in the main class accessible to all (or most) other classes?
Use the singleton design pattern.
Basically you return a static instance of an object and use that for all of your work.
Please see this link about how to use a singleton and also this stackoverflow link about when you should not use it
Warning: The singleton pattern involves promoting global state. Global state is bad for many reasons.
For example: unit testing.
It is not so bad idea to pass the logger and config to all the constructors if your logger and config is abstract enough.
Singleton can be a problem in the future. But it seams like a right choice in the project begin. Your choice. If your project is small enough - go with singleton. If not - dependency injection.
Why not use the system that's already in place? That is, redirect std::clog to output to a file and write to std::clog.
std::fstream *f = new std::fstream("./my_logfile.log")
std::clog.rdbuf(f->rdbuf());
std::clog << "Line of log information" << std::endl;
I'd agree with some kind of singleton approach. You definitely don't want to pass logger objects around all over the place. That will get very boring very quickly, and IMHO is a worse design than just having a plain global object.
A good test of whether you've got a good solution is the steps required to get the logging working in a function that needs it.
If you have to do much more than
#include "Logger.h"
...
void SomeFunction()
{
...
LOGERROR << "SomeFunction is broken";
...
}
...
then you are wasting effort.
Logging falls under the realm of 'separation of concern' as in aspect orient programming
Generally logging is not a function or concern of an object (for example, it does not change the state of the object; it is merely a mechanism for observing/recording the state, and the output is essentially disposable in most contexts)
It is an ephemeral and often optional side function that does not contribute to the operation of a class.
An object's method may perform logging, but the logging may be done there because it is a convenient place to do it or that point in the code execution stream is where one desires the state to be recorded.
Because C++ does not provide facilities for defining aspects, I tend to simply keep essentially external ephemeral objects like loggers global and wrap them in a namespace to sort of contain them. Namespaces are not intended for containment so this is kind of ugly, but for for lack of anything else it is convenient and is far less ugly and inconvienent than passing loggers in formal parameters or referencing them in all the objects you want to log. This also makes it easier to remove the logger if at some point I decide I no longer need the logger (I.e. if it was only used for debugging).
Don't know if this is helpful in your situation or not, but in MFC, there was/is an application class.
I use to throw things like this into that class.
I assume you are not using MFC, but if you have an application class or something similar, this might be helpful.
Why not use log4cxx?
Such problems are solved long ago and widely used by many.
Unless you're building some very special logging system of your own... In such case, I'd use Factory pattern which would create loggers for anyone interested (or giving away existing instance if it's singleton). Other classes would use factory to obtain the logger. Passing loggers in constructor parameters is a bad idea, because it couples your class with logger.
Why has no one thought of heritage and polymorphism? You could also use an abstract factory with that singleton ;)
Simply pass your main class into the constructor of the other classes that you want to have access to "everything"
Then you can provide access to the logger etc. via member properties.
(Forgive my C++ syntax, this is just a made-up language called "C++ confused by VB")
e.g.
Class App {
Private m_logger;
Private m_config;
Public logger() {
return m_logger;
}
Public config() {
return m_config
}
}
Class Window1 {
New( anApp ) {
}
....
}
I guess Service Locator will do. That you'll have to either pass around in constructors, or have a globally accessible static member function in some well-known location. The former option is much more preferable.
I would avoid the singleton pattern.
Too many problems when it comes to testing and all that (see What is so bad about singletons?)
Personally I would pass the logger etc into the constructor. Alternatively you can use a factory to create/pass a reference to the resource.

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.