IMO, C++ has the following huge benefits.
1. Ambient performance. If you need a fast program and don't have a tight loop you can optimize, C++ makes ordinary behavior fast.
2. RAII is a very clean and understandable design paradigm.
3. The idiom of using "const" everywhere plus widespread copying of values makes "spooky action at a distance" way less common when doing OOP or imperative programming.
RAII is a damned useful idiom too, makes writing safe code that much easier.
Tooling for C++ is pretty damn good in all the usual platforms
If you pass a unique_ptr it has to have redirection through a pointer, so it isn't quite zero cost.
However, since the entire point of using a smart pointer is to control the ownership I'm not that bothered.
It has a null check on destructor (and a delete of course), which is good enough for "zero cost" to me
I guess it is more complicated than i thought, but i think it is fair to compare them pointers too. Because most of the time you will probably need to store it as a pointer
At any rate, the definition of “zero cost” isn’t “it’s the same as a raw pointer”. Rather, it should be read as “its cost is the same as the equivalent functionality rolled by hand”. Shared_ptr implements a ref counting mechanism, which, absent a real GC, is necessary for actual shared ownership.
That's why shared_ptr has horrible performance, the spec requires that the control block is thread-safe. Perf tanks due to the atomic load/stores. If you roll your own with a standard load/store you'll see significant performance increase which means it's definitely not zero-cost.
This is why Rust explicitly went with Arc/Rc[2] so you don't have to pay that cost(although ambiguous ownership I would argue is a pattern you should try to eliminate anyway).
[1] https://en.cppreference.com/w/cpp/memory/shared_ptr
[2] https://doc.rust-lang.org/std/rc/struct.Rc.html / https://doc.rust-lang.org/std/sync/struct.Arc.html
It is true that the ref count is kept atomically, which allows accessing two distinct shared pointers that happen to point to the same object from different threads. This is pretty much a requirement to support the baseline distinct object thread safety (aka "as safe as int), but it is not what the unqualified "thread safe" normally refers to.
/pedantic
Anyway, it is true that with shared_ptr sometimes you might end up paying for what you do not use, but doing otherwise would have made any use of shared_ptr in threaded applications extremely unsafe so it was felt that in this case the cost was worth it for a vocabulary type object.
What kind of definition is that? Zero cost is exactly that - 0 cost, the same performance as if you were not using the abstraction. The alternative to an abstraction is not "my hand-rolled implementation of said abstraction" - it is not using the abstraction, at all (but using lower-level mechanisms to achieve the same goal). 0-cost is used to tell people "you will still achieve the same performance by using the abstraction - and you gain additional benefits (safety, readability etc)". If I can get better performance with raw pointers, then smart pointers are not zero cost (it's still a good idea to use them instead of raw pointers! Just, let's stop pretending they are zero-cost)
Most of the abstractions (E.g. iterations) are zero cost as opposed to additional functionality like shared pointers or resizable vectors.
i.e. there is no way to end up with faster code that does the same thing, without using the abstraction.
This is the very definition of zero cost abstractions.
Oh yes, that would really be awesome if that's the case. Wikipedia has a section regarding "Compiler diagnostics" when Concepts are used, the precision of the error message demonstrated is SO MUCH better than what you get with templates!
https://en.wikipedia.org/wiki/Concepts_(C%2B%2B)#Compiler_di...
Code example:
std::list<int> l = {2, 1, 3};
std::sort(l.begin(), l.end());
Example with templates: In instantiation of 'void
std::__sort(_RandomAccessIterator, _RandomAccessIterator, _Compare) [with _RandomAccessIterator = std::_List_iterator<int>; _Compare = __gnu_cxx::__ops::_Iter_less_iter]':
error: no match for 'operator-' (operand types are 'std::_List_iterator<int>' and 'std::_List_iterator<int>')
std::__lg(__last - __first) * 2,
...
... // continues for 50+ lines
Example with concepts: error: cannot call function 'void std::sort(_RAIter, _RAIter) [with _RAIter = std::_List_iterator<int>]'
note: concept 'RandomAccessIterator()' was not satisfiedA good meta programming language would be one that's as easy to program as a general language. lisp, nim, etc...
I have a lot of experience with many different types of metaprogramming (cl macros, Rust macros, template Haskell (and Typeable/Generic), ... even CLR code generation) and C++ templates are better than everything I've used other than Common Lisp once you really understand them. A really common C++ theme I see is people that don't understand things railing against them (I used to be in this camp myself, so I can identify with the sentiment).
Templates allow you to choose at will between nominal/structural subtyping (in a way), perform type-level logic, generate code that can be thread-safe or lock-free at the caller's whim... They are very powerful, much more than most devs realize, and if you understand C++, writing them is not difficult.
The "really understand them" part is, of course, the hard part. You need to understand the core language and the template language to be effective with them. I can see why even some experienced C++ developers shy away from templates.
The attitude with templates seems to be that if something is at all possible with hacks then there doesn't need to be any language support added, even if it would be vastly simpler to read and write and probably to compile. I don't think that works out well.
Generally I find the best use of templates is the most basic: you want to write some code that operates on duck-types. As long as one is able to control themselves and pick the right use cases for maintainability, templates are simple enough. In my experience, this is very doable.
Concepts are also a really cool way to rein in which types are accepted as a template parameter and have a lot of potential to make templates easier to understand and teach. To me, this is the most exciting c++20 feature.
I certainly understand metaprogramming, but navigating very dense C++ templates is one of the most complicated things I've had to do in my life. One or two levels of abstraction and you will lose your ability to hold everything you need to solve a problem in your head, and after a few dozen lines the source code is unreadable.
> You need to understand the core language and the template language to be effective with them.
this is a bug.
I also don't really see how requiring understanding of a language to generate that language could be considered a bug - every macro system carries that requirement. C++ just happens to be (much) more complex than most languages (and I do agree that a large amount of that complexity is probably not necessary).
I should be more clear about what I meant on the bug. C++ templates force you to understand the entirety of the language at once and hack around its edges because it doesn't support actual meta programming. It's hard for me to come up with a concrete example, but my experience writing some advanced compile-time evaluation with SFINAE patterns left me forgetting how things worked within minutes of typing them. Compare to say Rust, where the generics implementation is much cleaner and macro system better flushed out and easier to read/understand. Or the LISPs where your macro is just more LISP code.
And not for nothing, templates destroy compile times. They take a long time to write and edit and make everyone else using them work slower. All told, templates do not make it easier to write C++ except in trivial cases and first-order abstractions.
I do agree that you can go insane with templates and have a bad time. You just have to choose well. However if you have a problem with there existing other problematic code in the same language (that may be separate from your code), then C++ is maybe not the best fit. There's a lot of C++ out there.
I find it much more pleasant to write, e.g., ODBC client code in C++ than in C, and templates have a lot to do with that. I'm not an expert with Lisp macros or other reportedly superior meta-languages, but I will say that when I write generic code in C# or Java, I really miss the power of C++ templates.
Template syntax is pretty awful, and accomplishing what I want can involve some really strange idioms, like SFINAE. The ergonomics are slowly improving with type deduction, constexpr, and now concepts.
Nowadays C++ and a powerful multi-paradigm programming language quite straightforward to use if you forget the word “C” in its name.
If would be a good instructional language if people didn’t fall into the lazy “a horse is a king of animal” OO trope.
But, at least, you no longer have to iterate over arrays with size-1, (size-1)-1 etc these days. We have variadic template expansion, we have the (ugly, still not decent design, but useful) std::integer_sequence , and better still - we have pretty strong constexpr capabilities.
I do meta every day, meta-meta often, and triple-meta occasionally. The rules language for my Expert System is a true meta-language, because I designed it to (among other things) specify the manipulation of computer languages. So its domain knowledge is about the nature of computer languages and how to automate their assessment / analysis, transformation / re-engineering, translation, and generation.
To give a real-life example, we used our Expert System to automate the translation of complex compiler front- and back-end code from a proprietary system language to C++ for a major computer manufacturer. The translation rules don't really care what the code is doing; they care how the code is doing it. The compiler team created new templates and classes to provide the functionality their system language had that C++ doesn't, and we adjusted our translation rules to ensure that the translated code invokes those templates and classes in a clear, effective, efficient, and readable way.
C++ templates are just a compile-time lazily-evaluated Lisp.
As always, the criticism of C++ comes down to "programming is hard, let's go shopping".
If you don't want to learn and you just want to do the bare minimum to keep your 8 hour coding job, there's already plenty of languages that nail this niche. C++ obviously is not for you, just move on and don't make a redundant comment.
https://people.redhat.com/~rjones/bitstring/html/Bitstring.h...
D is far more powerful, especially when you consider that it's had working constraints for (?) something like a decade now.
Simple example, try to express this in C++ without a windows full of syntax-soup (https://d.godbolt.org/z/Toc8ob), the template constraint is one line, and I can pass anything into a template using alias be that templates, a string etc.
Passing strings into a templates is a very common trick for generating code at compile time in the D standard library, although it wouldn't work in C++ due to how slow C++ can be to compile some times.
https://www.youtube.com/watch?v=QM3W36COnE4 Here's an example of parsing regular expressions in C++ at compile time. Code here: https://github.com/hanickadot/compile-time-regular-expressio...
* RAII
* lambdas
* templates
* function overloading
* operator overloading (used judiciously)
* inheritance and interfaces (used judiciously)
* an extensive standard library
* exceptions (depends on the project)
For me, the advantages of C++ over C are obvious and IMO there's no reason to use C except for legacy projects or platforms which don't have a C++ compiler.
Of course, C++ has lots of warts and things to complain about, but OP asked for the positive things :-)
I could go on about the bad parts, but the good parts
1. lambdas
2. constexpr
3. threads
These additions did make C++ feel a little more modern.
And this is the "Vanilla" version of the features. In C++17 and C++20, there is all kinds of goodies like concepts and modules that I'm personally excited about.
Hate it all you want, but it's an amazing language.
In fact, it's the one major feature I'd love to start using right away that I know would be immediately useful, but the compiler support isn't there yet. According to this [1], Clang has partial support [2], while GCC has no support at all.
Finally we got modules, concepts will put an end to the fame of endless kilometres of error messages and compile time programming almost allows for static reflection.
It certainly has a lot of warts, but over the past decade, it has become easier and more straightforward to write code in various styles which used to be possible-but-a-pain (like functional programming), or not quite possible.
So with C++ you get performance + backwards compatibility + paradigm flexibility for the price of difficult, sometimes ambiguous syntax, some historical baggage you need to ignore, and slower compilation time. It's a decent tradeoff IMHO.
Specifically, regarding C++20:
* std::span is the best thing since sliced bread. How was this not in the library already? Cuh-razee... https://stackoverflow.com/q/45723819/1593077
* I'm happy that ranges support is inside the language. I can now `sort(my_container)` rather than the clunky `sort(my_container.begin(), my_container.end())` for example. And there are a bunch of useful lazily-evaluted range views. I only wish more of the ranges library could have been added. And I hope the compilation of ranges isn't too slow.
* Modules can now start replacing include files. Initially, this will only be a theoretical possibility, but within several years, no longer will your compiler have to deal with 100,000 lines of text or so per translation unit: It will be like in Java and other languages, where it's just your current file that needs to be compiled and the rest is already compiled. Of course the transition will not be smooth (feature macros, conditional compilation - not obvious to me how to replace them when using modules), but this is a good direction. We could see faster compilation times and content suggestions in IDEs.
* Expanded constexpr support means we can do more work once, at compile time, rather than repeating it at run-time (e.g. dynamic memory allocation - so you can have constexpr std::vector).
* Coroutines are something interesting which I am not familiar with (except the very rough general idea of different control flows being switched between. I can at least say it's interesting to look into.
* libfmt string formatting - Yes, yet another way to format strings: printf-style, iostreams, and now the "Python style", I guess you could say? It combines some benefits of both of the previous ones.
* std::source_location - you know how, if you're writing some error-handling function, you usually need to wrap it in a macro which gives you the filename and line number? Well, that's going away now. I know it's just a minor thing, but I hate having those macro'd error handlers.
* You can now tell the compiler to use a generated equality and comparison operators; this saves you boilerplate. Although in the C++ tradition, this capability is defined in a somewhat convoluted way under the hood.
Highlights for me:
- Type deduction -- basically using auto for variable declarations.
- Move semantics makes RAII actually usable since you can make heavy / important objects but then move them elsewhere and still have their lifetime be automatically managed. I use this in my game engine to wrap physics bodies etc. so that they are automatically removed from the scene when the component containing them is dropped (I'm using an ECS). A neat thing also is you can delete copy constructors and force certain types to be "move-only."
- Having been in C-land for a bit, I'm appreciating the ready availability of std::vector and std::string again. Also std::array is awesome.
- Lambdas are amazing. I often make simple control structure utilities in my modules that accept lambdas, and they are often inlined. I don't often do lambdas where I 'save them and call them later' -- they are mostly immediately called. This makes it safe to use reference captures.
As for C++20 I am mostly interested in seeing how it goes with modules Also the `requires` keyword will simplify some of my uses of `enable_if`.
A lot of the good stuff is also due to ecosystem and tooling vs. just language. My game works everywhere now: native macOS, Windows and iOS, but especially web due to Wasm! It also has an immediate mode API for rendering UI in Wasm, which I use along with some simple reflection to get an automatic entity inspector: https://m.imgur.com/dyUtL8f The entire gameplay code fits in like 700 lines: https://gist.github.com/nikki93/5893543a5e3d76a7858d54b74a4c... You can see how I don't do any pointer stuff or manual recource / memory management there at all.
Tbh in many cases with precompiled headers it almost feels like it builds about as fast as webpack. And then my "publish" is a simple rsync of static files to the server.
Another tooling / ecosystem thing lately has been godbolt.org which is wonderful for seeing immediately the asm that ur code generates. Which then makes you realize how good optimizing compilers for C++ are these days. I don't think other languages have come so far. And then with godbolt.org you can learn which constructs produce what code.
I'm using entt for the ECS: https://github.com/skypjack/entt you can see how it encourages the use of POD structs and non-OO code for the most part. It feels good to use C++ in that style as a C with the above features. I just basically don't use vtables / RTTI anymore. I do use templates a fair amount.
I do concede that this enthusiasm may have a lot to do with having had experience in C/C++ already for a while. If I was completely new to the language it'd be a lot harder. The backwards compatibility lets me keep all my experience (even if the point isn't to write exactly like how I wrote before, but to understand the motivation for the new features). I've also dug into Go, Rust, Nim, Common Lisp, Haskell, ... but weirdly modern C++ has been the best combination of ergonomics, control, and portability. Especially for Wasm you really just want deterministic resource management. I'd probably still combine it with Lua or JS for scripting eventually.
You do have to invest a lot of energy into learning the language and caring about the details, but I think C++ is very well positioned to reward you for that investment, and you are also rewarded continuously and early.
We all know the negative parts, any C++ related thread is always full of people repeating them over and over. What about some celebration time for now? A huge milestone for the language has been reached with C++20, can we share something positive about it for once?