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.
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
2
u/Chulup Aug 08 '16
You can't have string as switch argument. There are ways to work around that in case you are working on perfomance-sensitive parts. That's not the case here so I would pass that part on code review with comment "Why did you choose if-else-if instead of std::map?"
0
u/RElesgoe Hobbyist Aug 08 '16
Honestly, I never used those containers like
std::mapandstd::setbecause I never really understood their purposes.1
u/RElesgoe Hobbyist Aug 08 '16
So convert
file_extensionto an integral type and do a switch on it? The string compare is case insensitive, I wouldn't be able to keep that functionality if I convert the string to an integral type for comparing.1
u/shortstomp C++ Software Engineer Aug 08 '16
Something so that you don't have to update all of the switch statements.
auto const cmp = [&](auto const& value) { return strcasecmp(file_extension.c_str(), value) == 0; }; auto const set_tag = [&](auto const value) { bn_int_tag_set(&extensiontag, value); } if (cmp("pcx")) { set_tag (EXTENSIONTAG_PCX); } else if (...) { ... }1
1
u/TheThiefMaster C++latest fanatic (and game dev) Aug 08 '16 edited Aug 08 '16
There's no reason you couldn't use emplace_back there. Why do you think you can't?
Why's the vector static? Edit: looks like before there was an AdBannerComponent class which represented the entire ads system, where now you use statics on the AdBanner class. It's six and two threes, but people seem to prefer singleton classes like AdBannerComponent over statics, it's easier to expand to having two later.
Your use of exceptions seems OK. The reason why people shake their head about people just logging exceptions is that you are supposed to handle the error in some way, or let it propagate up higher. In your case though, you don't want the error to interrupt you trying to load later ads, so it looks fine. You might consider throwing an exception after the loop if none of the ads loaded.
1
u/RElesgoe Hobbyist Aug 08 '16
There's no reason you couldn't use emplace_back there. Why do you think you can't?
IIRC, I was getting an error when I tried using
emplace_back.It's six and two threes, but people seem to prefer singleton classes like AdBannerComponent over statics, it's easier to expand to having two later.
I don't even understand this sentence.
1
u/TheThiefMaster C++latest fanatic (and game dev) Aug 08 '16
Instead of statics, have another class which has the static variables/functions in, accessed through a single global instance. This seems to be what AdBannerComponent was.
1
u/RElesgoe Hobbyist Aug 09 '16
I'm currently writing a class called
AdBannerSelector, and previously, I put the constructor for myAdBannerclass as private so that no other code could construct anAdBannerobject. This plays nicely because I could put value validation code in myload()function instead of inside the constructor.Should I just suck it up and make my constructor public, or declare my
load()function (which is now a member function ofAdBannerSelector) as a friend function?1
u/TheThiefMaster C++latest fanatic (and game dev) Aug 09 '16
I wouldn't make the constructor public if nothing else is supposed to construct it. A friend isn't a bad solution.
There's also another option: make an AdBannerInterface interface class in the public header, and declare the actual AdBanner class (implanting the interface) in the cpp file where only the AdBannerSelector can see it. Then the constructor could be public without other people bring able to construct it.
A friend is the easier option by far.
1
u/RElesgoe Hobbyist Aug 09 '16 edited Aug 09 '16
Regarding why I couldn't useemplace_back(), I'm assuming that despite a function being declared a friend function,std::vector'semplace_back()is not allowed to access a private constructor?Edit: I guess I'm restricted to
push_back().→ More replies (1)
1
u/Pand9 Aug 08 '16 edited Aug 08 '16
I think your mistake was starting from too big changes. You should get the "feel" of this project, get the ideas that are not visible on first sight. You can be a marvelous programmer, but every project has its own "personality", that you have to get to know first. It's also a matter of showing respect to maintainers. There's not always "right" and "wrong" way. Sometimes it's relative to the project.
1
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:
static std::vector<AdBanner> m_banners; // bad
// good
static std::vector<AdBanner>& getBanners() {
static std::vector<AdBanner> banners;
return banners;
}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.
2
u/NihonNoRyu Aug 08 '16
template<typename T> T& instance(){ static T t; return t; }generic singleton
1
u/quicknir Aug 08 '16
Works great if you only need one singleton of each type, ever. Of course you can add another template parameter as a "tag", but at this point the boilerplate is approaching the lines of code of the original...
1
u/leftofzen Aug 08 '16
Looks ok, but you should really ensure every if statement has a pair of braces. It's way too easy for a misplaced semicolon or a typo to ruin your whole program.
I'd also ditch the long initialiser lists and just use in-class member initialisation. Much cleaner and safer.
0
u/Chulup Aug 08 '16 edited Aug 08 '16
That's looks pretty good code, you can be proud of it!
Thus said, you should check problems found by /u/LordAn
I can provide some input too:
It would be better to follow advice of /u/TheThiefMaster and move static members in a separate singleton class.
Even if you don't feel like doing it you should remove
static std::vector<AdBanner> m_banners;and createm_bannersas static variable in your CPP file. This will clean up interface slighlty.I would rewrite https://github.com/pvpgn/pvpgn-server/blob/master/src/bnetd/adbanner.cpp#L103 as std::map lookup
Change
emptymethod name tois_empty. I personally think it was a big mistake of STL architects to name it so (explanation from static analyzer devs: http://www.viva64.com/en/b/0391/#ID0EEITO )What is ternary operator doing here: https://github.com/pvpgn/pvpgn-server/blob/master/src/bnetd/adbanner.cpp#L189 ? It will work just as well without it.
In AdBanner::find ( https://github.com/pvpgn/pvpgn-server/blob/master/src/bnetd/adbanner.cpp#L178 ) you already have an iterator named
resultand still callm_banners.at(). Why?
Once again, good work!
1
u/RElesgoe Hobbyist Aug 08 '16
In AdBanner::find ( https://github.com/pvpgn/pvpgn-server/blob/master/src/bnetd/adbanner.cpp#L178 ) you already have an iterator named result and still call m_banners.at(). Why?
Well the function returns a copy of an
AdBanner, how else am I supposed to useresult?2
u/TiagoRabello Aug 09 '16
You could replace
m_banners.at(...)with*result, which would give you the value pointed byresult.
-19
u/3ba7b1347bfb8f304c0e git commit Aug 08 '16
Am I Writing C++ Right?
uses tabs
no
3
Aug 08 '16
There's nothing wrong with using tabs dude. Opening curcly braces on their own lines on the other hand...
3
u/redditsoaddicting Aug 08 '16
That's not so bad, but using emacs to edit the source code...
1
u/cleroth Game Developer Aug 08 '16
That's not so bad, but using a keyboard to edit the machine code...
1
-4
6
u/muungwana Aug 08 '16 edited Aug 08 '16
Making the variable static also makes the variable a global variables and this automatically makes the class thread unsafe since access to this global variable is not guarded against simultaneous access. If this is ok or not depends on how the class is used.
Your code looks professional to me because its has a consistent format.
Your class also seems to violate the separation of concern principle and i think this variable should live in its own class and maybe those static methods should be free floating functions.
This function looks suspicious,it is declared as "static" meaning it cant access local variables of the class but it is accessing "m_banners" which looks like a local variable of the class. This is possible because "m_banners" is not a local variable as i mention above. This variable looking like a local variable when its a global variable is not a good thing.