3 ms·
I started off writing C++ this way, basically writing it like it was C89. This is fine if you do not plan to share your work with others, but it's not well-wri
by Night_Thastus 3y ago
I started off writing C++ this way, basically writing it like it was C89.
This is fine if you do not plan to share your work with others, but it's not well-written C++. It will bite you later on. It's best to learn the C++ way of doing things. It will save you so much time and headache. Don't use character arrays, use strings. Don't use C arrays, use std::vector or std::array. Don't write your own lists or sets, use std::list/set or std::unordered_list/set. Don't use strcat when std::string operator + exists. Etc.
I personally rarely use smart pointers or make_shared/make_unique these days. I just don't need pointers. Most of the time allocation can be done without them, and when I need to pass things around I use references. There are exceptions for C APIs for cross-platform/cross-compiler work, of course. And sometimes library code needs it, ofc.
The STL and <algorithm> are your friend. They solve so many problems in a very elegant way. Learning them should be a priority.
I'd go easy on the OOP elements unless you know OOP programming very well. Just using classes as containers for data and functions is more than fine for C++ most of the time.
Writing your own templates can be a bit of a footgun until you understand them. Feel free to put that off awhile.
Don't mess with volatile and asm unless you are 100% sure that what you're doing needs it.
Also: Be cautious with use of auto. A bit here and there is fine, but too much and code can become unreadable. C++ is a typed language for a reason.
- hedora 3y agoIn particular, you don't need volatile unless you're writing hardware device drivers. If you're doing that, then you also need to understand the semantics of the memory mappings of the I/O pages you're writing. You also need to know about bus ordering and request coalescing guarantees for PCIe (or AXI, or whatever your embedded system uses). If that paragraph doesn't make any sense, and you think you need volatile then there are basically two possibilities: You're writing a Java program (which uses that keyword for something else), or you need std::atomic (or __sync_* for C) instead.
- gpderetta 3y ago> (or __sync_* for C) Actually even C has _Atomic these days!
- HarHarVeryFunny 3y ago> Be cautious with use of auto. A bit here and there is fine, but too much and code can become unreadable. Yes, although one place where "auto" should almost always be used is to declare iterators (not that one should be needing them so much nowadays), and I think harmless for range-based for loops "for (auto i : v)" although as you say there's definitely a convenience/readability trade off.