As I write earlier, I’m back to C++ after more than 20 years. A refresh was needed so I bought this (on the right side of the picture above) to catch up.
There’s exactly 21 years between those 2 books editions. In the distant early 90’s there was no Internet… This is partly why I bought a French version…
Anyway, I’d like to list widely used features in c# and their counterpart in modern C++. I’m thrilled that they’re available. The following list is about the features that I use, not the available features:
- var (c# 3) vs auto (C++11)
- lambdas expressions (c# 3 / C++ 11)
- captured variables vs capture clause
- Garbage Collection vs std::shared_ptr
var (c# 3) vs auto (C++ 11)
I have to say that I’m not a fan of var in c#. Of course, sometimes, this saves you from typing a lot of code. I’ve always used it with intellisense (quick info) to understand the type that is deducted automatically and then replaced var with that explicit type. I’ve decided to do the same in C++, because quick info (hover) is also available with Visual Studio Code.
Refer to item 2 of the Effective Modern C++ book or this link to know more about auto type deduction. I’m pretty sure that advices at the end of Eric Lippert’s blog post about using var could apply to auto as well.
lambda expressions (c# 3 / C++ 11)
We’re going back to 2007 (thanks to web archive) to learn about the infusion of lambdas in the c# language.
I’ve been using lambda expressions in c# mostly for one-off calls. The same applies to C++ so far.
captured variables vs capture clause
If a lambda is using outer variables, they need to be captured somehow. In c# and C++ the compiler generates a closure for you. As far as I can tell, there is no hint to tell the compiler about it to generate the unique closure class. This is tied to automatic garbage collection of objects.
In C++ you have the ability to provide a capture clause to specify the capture modes to escape the default ones. You have to ensure that your captured variable still exists when the lambda is invoked.
Garbage Collection vs std::shared_ptr (.NET / C++ 11)
Speaking of garbage collection 🙂 Well smart pointers are the old new thing. Seriously in C++ you’re still in charge of releasing objects. The power is that it is up to you. I still rely on Kate Gregory’s blog for insights and best practices when writing C++ code.
Final words
Please follow the C++ Core guidelines. I wish there was an extension to Visual Studio Code as there is a checker tool for Visual Studio.
I’ll update this post as I’m using new modern C++ features. Stay tuned.