-
Notifications
You must be signed in to change notification settings - Fork 26
Coding guide Cpp practices
Péter Kardos edited this page Jan 29, 2018
·
4 revisions
C++ is a big and somewhat bloated language. Guidlines presented here are meant to ensure that code will be clean, less error-prone, maintainable and high performance.
Direct use of new and delete expressions is strongly discouraged. Modern C++ gives much better ways than that.
- Smart pointers: Use unique pointers when the owner certainly has a longer lifetime than all references to the heap object. Use shared pointers when there are no lifetime guarantees. Use weak pointers, if you don't care if the object is deleted unexpectedly. While there should always be a smart pointer owning the object, raw pointers can be passed around if it is ensured by architecture or design that the object outlives the raw pointer, and when using smart pointers may become a performance issue. Performance-wise, unique pointers have virtually zero overhead, while shared pointers must use atomic operations on creation and deletion (moves are still "free"), which is significant in big numbers.
- Containers: unique pointers are good for single objects, but vectors are a nicer way to dynamically allocate arrays. Use pre-allocated vectors, lists or deques depending on access patterns. Consider using std::array instead of pure C-like arrays.
- RAII and exceptions: the above described stuff is called RAII. In a nutshell, you specify who will destroy the object just as you allocated it. This ensures that objects won't leak. Since the engine uses exceptions, almost every line is an exit point from a function. Without RAII, every line should be wrapped in a try/catch to avoid leaks, and now it's all fine.
C++11, 14 and 17 brings a lot of tools which make the language much more expressive, thus, their usage is required. There should not be code written with old paradigms.