Should I ever use __throw_logic_error? - c++

I've stumbled upon a piece of code that uses a function std::__throw_logic_error to throw exceptions. This function is declared in functexcept.h and apparently does the same as throw logic_error(...). Is there a difference? What is the function for? When, if at all, should I prefer it?
Thank you.

No, don't use it (unless you really know what you're doing). It's internal to the implementation (as all __ names are).

In general, you shouldn't use it.
The two underscores at the beginning of the name are an indication that it's a compiler-specific addition, and probably it's not even meant for "public" use, but just as a helper for internals of the standard library (I suspect that it's there to support e.g. using the library without exceptions, but I'm just guessing).
Just use throw.

Related

What is the equivalent standard function of the "AfxIsValidAddress" function?

I was using an MFC-project, that shall be proted in a platform-independent environment, using std-function instead of MFC/AFX.
For example: instead CString the std::string, instead CMutex the std::mutex will be used.
What is the platform-independet, C++11 std::-equivalent of the MFC function "AfxIsValidAddress"?
There is not something similar to AfxIsValidAddress() in the standard library and it appears that the function doesn't actually do that much validation anyway.
See AfxIsValidAddress (and Others) Don’t Work as Advertised which says the function ends up just doing a check against NULL. It also has this to say about the family of valid address check functions:
There are several Win32 API similar in functionality: IsBadWritePtr,
IsBadHugeWritePtr, IsBadReadPtr, IsBadHugeReadPtr, IsBadCodePtr,
IsBadStringPtr. It has been known since at least 2004 that these
functions are broken beyond repair and should never be used. The
almighty Raymond Chen and Larry Osterman both discuss the reasons in
detail, so just a short rehash: IsBad*Ptr all work by accessing the
tested address and catching any thrown exceptions. Problem is that a
certain few of these access violations (namely, those on stack guard
pages) should never be caught – the OS uses them to properly enlarge
thread stacks.
I think it is better to just follow standard C++ procedures to check that a pointer is not a nullptr or better yet to limit the use of pointers as much as possible.

In which cases will the restrict qualifier applied to a return value have an effect?

If I have a member function declared like so:
double* restrict data(){
return m_data; // array member variable
}
can the restrict keyword do anything?
Apparently, with g++ (x86 architecture) it cannot, but are there other compilers/architectures where this type of construction makes sense, and would allow for optimized machine code generation?
I'm asking because the Blitz library (Blitz++) has a whole slew of functions declared in this manner, and it doesn't make sense that someone would go in and add the restrict keyword unless it actually does something. So before I go in and remove the restrict's (to get rid of compiler warnings) I'd like to know how I'm abusing the code.
WHAT restrict ARE WE TALKING ABOUT?
restrict is, as it currently stands, non-standard.. which means that it's a compiler extension; it's non-portable in the sense that the C++ Standard doesn't mandate its existance, nor is there any formal text in it that tells us what it is supposed to do.
restrict is currently compiler specific in C++, and one has to resort to the compiler documentation of their choice to see exactly what it is doing.
SOME THOUGHTS
There are many papers about the usage of restrict, among them:
Restricted Pointers - Using the GNU Compiler Collection
restrict - wikipedia.org
Demystifying The Restrict Keyword - CellPerformance
It's hinted at several places that the purpose of restrict is to qualify pointers so that the compiler knows that two pointers in the same scope doesn't refer to the same memory location.
With this in mind we can easily see that the return-type has no potential collision with other pointers, so using it in such context will generally not gain any optimization opportunities. However; one must refer to the documented behaviour of the used implementation to know for sure.. as stated: restrict is not standard, yet.
I also found the following thread where the developers of Blitz++ discusses the removal of strict applied to the return-type of a function, since it doesn't do anything:
Re: [Blitz-devel] type qualifiers ignored on function return type
A LITTLE NOTE
As a further note, here's what the LLVM Documentation says about noalias vs restrict:
For function return values, C99’s restrict is not meaningful, while LLVM’s noalias is.
Generaly restrict qualifier can only help to better optimize code. By removing 'restrict' you don't break anything, but when you add it without care you can get some errors. A great example is the difference between memcpy and memmove. You can always use slower memmove, but you can use faster memcpy only if you know that src and dst aren't overlaping.

Strange Pattern: all functions/methods return error-code using the same type in C++

In my last two projects I've seen the strange guideline, "All Methods/Functions should return error-code using some common ERROR_CODE type". In both projects ERROR_CODE is an int typedef.
Is there any good reason doing it in C++? Some MISRA requirement or something like that?
I can see only disadvantages:
If a function should return a value, it is done by argument reference. e.g.:
string s;
ERROR_CODE err = getString(s);
The importance of a function is not obvious. All looks the same. The list of errors conntains hundreds of errors from low level errors to some domain specific errors.
Have you experienced this programming style? Are there good arguments against it or for it?
I think it's a very bad style for several reasons.
Like you've said, it forces you to pass pointers/references to store the actual result of a function.
Like you've said, the unified error code is ugly because it's trying to unify all sorts of errors from all sorts of domains.
It creates an artificial dependency of all the program's modules on the error code system, making it awkward to reuse a single module or small subset of modules in other programs.
Further, since some of the error codes are domain-specific, it's actually introducing dependencies between unrelated object types/modules, since they're all dependent upon a component that's dependent upon the union of all of their possible error types.
My view is that any function/method which has more than a small manageable number of ways it can fail is either overly complex or poorly factored, probably both.
If you really want to return error codes, I would swap things around and pass the pointer to the error code as an argument to the function, and make the actual result the return value. Then I would choose one of these two approaches for implementing the error codes:
The simple way: throw away all abstraction of the error code and simply use int with a few universal error classes.
The heavy object oriented way: Provide a pointer to an internal "error object" where the base class is very abstract and can be shared between all components without introducing any dependency, and where each component defines its own component-specific error objects if needed.
A better approach if you're using C++ would probably be using exceptions...
I've seen it.
kernel programming is that way, except when only one error is possible.
It doesn't sound like a great idea, but neither all that bad of one.
It's not unusual for teams to agree on a common means of returning errors, since this helps in creating a common 'look and feel' to the project's code, just like any other team-wide coding convention. This could help new team members to understand the overall picture quicker, and make maintenance within the team of other peoples' code a little more intuitive.
It's surprising to me that a C++ project is unifying behind errors rather than exceptions, however. There's a discussion of the pros and cons of using exceptions vs error codes here.
I guess one argument in favour of error code handling is if you are using a C-style API that leads you into this approach (cough... Win32... cough).
This idiom is quite common, especially in the C world.
Even though I don't use it myself and I think it makes more harm than good (more on that in the other answers), I do find an advantage of it: a consistent way to report unexpected errors to the call site. Something like the errno variable, but easier to use.
For instance, consider a set of functions:
int a();
std::string b();
double c();
std::list<long> d();
Each of the above functions would indicate the failure in a different way: a() could return an -1, b() an empty string, c() a 0.0 and d() an empty list. That's inconsistent and not quite intuitive. Now imagine a function, whose range covers the entire possible range of the type it returns. That's even worse.
Some APIs also do:
int x(bool* ok);
But that also pollutes each function with an additional argument.
In C, there aren't many possibilities to do in a nice way, unfortunately, if you really need to design such an API that would indicate the different types of failure. In the C++ world, however, you can just use exceptions.
I've seen the argument that when linking to a C++ library compiled by another compiler than is used to compile your binaries, exceptions might not work. While this non-working may totally be true, in actuality, even the linking process need not work (although everyone may be sticking to the standards), so, theoretically, this argument is void. In practice however, it may be (I don't have experience here, sorry), that name mangling conflicts rarely arise, alignment conflicts rarely arise, and, well, all other implementation specific stuff is widely agreed upon, except for exceptions.
Second argument I've seen is run-time performance. While stack unwinding in case of an exception is expensive, I've not yet seen a fair benchmark that compared exceptions to a realistic amount of return code checking.
In my typical C++ I use a mix. I use the slower exceptions for stuff that I really don't expect to happen frequently or code paths that are measured to be rarely executed, but return codes for stuff that is more likely to break and probably called frequently.
Throwing exceptions in a tight loop because some funny condition holds true in every iteration is not cheap (assuming the loop body handles it).

What the reasons for/against returning 0 from main in ISO C++?

I know that the C++ standard says that return 0 is inserted at the end of main() if no return statement is given; however, I often see recently-written, standard-conforming C++ code that explicitly returns 0 at the end of main(). For what reasons would somebody want to explicitly return 0 if it's automatically done by the compiler?
By being explicit you are explicitly showing your intent.
By relying on something implicit you could have 2 cases: 1) You intended it, 2) You forgot it.
Because it just looks weird to not "return" something from a function having a non-void return type (even if the standard says it's not strictly necessary).
Makes it clear to other programmers that you didn't just forget to put the return statement there.
Some compilers may issue a warning if you don't return anything.
Shows explicitly what the function returns.
Many programmers don't know about this rule.
Misunderstanding. There's simply no reason to, and if someone doesn't know that they'll add return 0;.
Just because your code complies with the standard, who says your code is going to be run through a compliant compiler? Believe it or not, people do use compilers besides just recent versions of GCC and Visual C++.
And of course there's the explicit intent thing that everyone else has mentioned.
It makes behavior of the code explicit.
Because some people don't know. Not necessarily the people who wrote that code (although that's also possible), but some people out there. Explicitly writing return 0; is being nice to them.
Also, as a convention it makes the language more uniform, which aesthetically is important to at least me.
Because this is how they did it 30 years ago. It is more of a convention IMO.
I often do it because I often compile code for straight C, so I either type it in out of habit or because the snippet I created main() from has the explicit return. There's no reason to remove it, so it usually stays.
Then again, there are times when I won't bother typing it in (maybe I realized I didn't need it) or I may have used a different snippet.

How can I trust the behavior of C++ functions that declare const?

This is a C++ disaster, check out this code sample:
#include <iostream>
void func(const int* shouldnotChange)
{
int* canChange = (int*) shouldnotChange;
*canChange += 2;
return;
}
int main() {
int i = 5;
func(&i);
std::cout << i;
return 0;
}
The output was 7!
So, how can we make sure of the behavior of C++ functions, if it was able to change a supposed-to-be-constant parameter!?
EDIT: I am not asking how can I make sure that my code is working as expected, rather I am wondering how to believe that someone else's function (for instance some function in some dll library) isn't going to change a parameter or posses some behavior...
Based on your edit, your question is "how can I trust 3rd party code not to be stupid?"
The short answer is "you can't." If you don't have access to the source, or don't have time to inspect it, you can only trust the author to have written sane code. In your example, the author of the function declaration specifically claims that the code will not change the contents of the pointer by using the const keyword. You can either trust that claim, or not. There are ways of testing this, as suggested by others, but if you need to test large amounts of code, it will be very labour intensive. Perhaps moreso than reading the code.
If you are working on a team and you have a team member writing stuff like this, then you can talk to them about it and explain why it is bad.
By writing sane code.
If you write code you can't trust, then obviously your code won't be trustworthy.
Similar stupid tricks are possible in pretty much any language. In C#, you can modify the code at runtime through reflection. You can inspect and change private class members. How do you protect against that? You don't, you just have to write code that behaves as you expect.
Apart from that, write a unittest testing that the function does not change its parameter.
The general rule in C++ is that the language is designed to protect you from Murphy, not Machiavelli. In other words, its meant to keep a maintainance programmer from accidentally changing a variable marked as const, not to keep someone from deliberatly changing it, which can be done in many ways.
A C-style cast means all bets are off. It's sort of like telling the compiler "Trust me, I know this looks bad, but I need to do this, so don't tell me I'm wrong." Also, what you've done is actually undefined. Casting off const-ness and then modifying the value means the compiler/runtime can do anything, including e.g. crash your program.
The only thing I can suggest is to allocate the variable shouldNotChange from a memory page that is marked as read-only. This will force the OS/CPU to raise an error if the application attempts to write to that memory. I don't really recommend this as a general method of validating functions just as an idea you may find useful.
The simplest way to enforce this would be to just not pass a pointer:
void func(int shouldnotChange);
Now a copy will be made of the argument. The function can change the value all it likes, but the original value will not be modified.
If you can't change the function's interface then you could make a copy of the value before calling the function:
int i = 5;
int copy = i
func(&copy);
Don't use C style casts in C++.
We have 4 cast operators in C++ (listed here in order of danger)
static_cast<> Safe (When used to 'convert numeric data types').
dynamic_cast<> Safe (but throws exceptions/returns NULL)
const_cast<> Dangerous (when removing const).
static_cast<> Very Dangerous (When used to cast pointer types. Not a very good idea!!!!!)
reinterpret_cast<> Very Dangerous. Use this only if you understand the consequences.
You can always tell the compiler that you know better than it does and the compiler will accept you at face value (the reason being that you don't want the compiler getting in the way when you actually do know better).
Power over the compiler is a two edged sword. If you know what you are doing it is a powerful tool the will help, but if you get things wrong it will blow up in your face.
Unfortunately, the compiler has reasons for most things so if you over-ride its default behavior then you better know what you are doing. Cast is one the things. A lot of the time it is fine. But if you start casting away const(ness) then you better know what you are doing.
(int*) is the casting syntax from C. C++ supports it fully, but it is not recommended.
In C++ the equivalent cast should've been written like this:
int* canChange = static_cast<int*>(shouldnotChange);
And indeed, if you wrote that, the compiler would NOT have allowed such a cast.
What you're doing is writing C code and expecting the C++ compiler to catch your mistake, which is sort of unfair if you think about it.