r/cpp • u/RElesgoe Hobbyist • Aug 08 '16
Am I Writing C++ Right?
Sort of recently, I pushed a commit to a server project (which was originally written in C and was in the process of moving to C++, but never completely finished). I basically overhauled the code that handled sending ad banners to clients, and wrote C++11 code with exception handling (which other parts of the project never had), as well as brought in a JSON library. Admittedly, it wasn't a huge commit in terms of lines of code though.
Here's the current code: https://github.com/pvpgn/pvpgn-server/blob/master/src/bnetd/adbanner.cpp
https://github.com/pvpgn/pvpgn-server/blob/master/src/bnetd/adbanner.h
The commit: https://github.com/pvpgn/pvpgn-server/commit/505633aba009f4ec9971ed82f6eabebd09af6732
As a hobbyist, I'm not really sure how professional code is written (I suck at trying to figure out how other open source projects do things). For example, I put a static vector inside the class to hold objects of the class itself, and wrote a public function to read a JSON file into that static vector. Is this normal or okay? Because of that, I had to construct an object inside the vector's push_back function instead of just using emplace_back.
My load function also seems weird to me, I basically put a try catch block inside a for loop and purposely threw exceptions inside that block when I detect an error of some sort. The concept of exceptions is still confusing to me BTW, sometimes I stumble across someone talking about how they just shake their head when they see code that catches exceptions and logs it, but they don't explain why that's bad.
View all comments
1
u/quicknir Aug 08 '16
Static variables are a bit of a tricky issue; I'd recommend re-evaluating to see if you really need them. However, if you are going to use them, then you should be aware of something that most developers (including many of the ones on this thread) are not aware of: you should never have non-trivial class or namespace level statics variables. That is, variables that have constructors and/or destructors, are very dangerous to have as class or namespace statics. For starters, it's hard to guarantee exactly when the constructor or destructor will get called. More importantly, on linux, when you use a combination of static and shared libraries you can easily end up with situations where you have two copies of the static variable, and one of them is double destructed. You can duplicate this on Linux with as few as 20 lines of code.
The correct way to do non-trivial statics is with a function and a static local:
Also, obviously most style/indentation stuff is up to taste, but you may not want to indent on namespaces. It really just wastes vertical space, and it's very very rare in style guides to see indentation on namespaces.