1

I'm a member of project which uses c++11. I'm not sure when I should use error code for return values. I found RVO in c++ works great even if string and struct data are returned directly. But if I use a return code, I cannot get the benefit of RVO and the code is a little redundant.

So every time I declare function, I couldn't decide which I should use for a return value. How should I keep a consistency of my code? Any advice will help me.

// return string
MyError getString(string& out);
string getString();

// return struct
MyError getStructData(MyStruct& out);
MyStruct getStructData();
Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
jef
  • 3,890
  • 10
  • 42
  • 76

1 Answers1

3

Usually, using exceptions instead of error codes is the preferred alternative in C++. This has several reasons:

  • As you already observed, using error codes as return values prevents you from using the return values for something more "natural"
  • Global error codes, are not threadsafe and have several other problems
  • Error codes can be ignored, exceptions can not
  • Error codes have to be evaluated after every function call that could possibly fail, so you have to litter your code with error handling logic
  • Exceptions can be thrown and passed several layers up in the call stack without extra handling

Of course there are environments where exceptions are not available, often due to platform restrictions, e.g. in embedded programming. In those cases error codes are the only option.

However, if you use error codes, be consistent with how you pass them. The most appealing use of error codes I have seen that does not occupy the return value spot and is still thread safe was passign a reference to a context object in each and every function. The context object would have global or per-thread information, including error codes for the last functions.

Arne Mertz
  • 24,171
  • 3
  • 51
  • 90
  • Thank you for your practical advice. As n.m mentioned, exceptions are suitable in that developers are forced to handle errors. – jef Aug 21 '15 at 05:58