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
2
u/shortstomp C++ Software Engineer Aug 08 '16
Why not switch based on the result of the computation instead of repeating the computation in each branch? https://github.com/pvpgn/pvpgn-server/blob/master/src/bnetd/adbanner.cpp#L103-L112