3 ms·
Here's the thing, there is a nice way (well, more than one) to blend highly tuned low-level C code with clean, modern C++. I have to do it: I work on high perfo
by alfalfasprout 11y ago
Here's the thing, there is a nice way (well, more than one) to blend highly tuned low-level C code with clean, modern C++. I have to do it: I work on high performance algorithmic trading systems.
You want to keep raw pointers, etc. confined to private class members, initialize memory only within the constructor (if possible), and free memory at the destructor. The user/public API should not expose unsafe stuff. With all this, RAII will give you a nice expectation of lifetime, etc. Plus you're able to use something like tcmalloc.
I often find a difficult issue arises when you have a large data structure that you want to free before it goes out of scope (to reclaim some memory). In this case, adding a "clear" method that frees the internals is handy. The destructor will call clear() but you can call it at any time. No harm done if it's called twice.
The next thing is const-correctness: if you follow it then any C-like code underneath should be relatively safe.
Not using copy constructors is just awful. Memcpy has a time and a place: at the low level (eg; I use it for serializing to a buffer). If you're using memcpy for classes you're probably doing something wrong.
Exceptions are a place where you see a wide gamut of safety. Some people don't use them at all: which isn't great. Others add hundreds of lines of code by wrapping everything in a try/catch. Not sure where I stand here, honestly. There's a point where you're catching exceptions that just aren't going to happen...