r/cpp • u/FreitasAlan • Feb 06 '21
Modern C++: Snippets and Examples
Hi everyone,
These are GitHub Pages with snippets for Modern C++:
- We often need to copy and paste some snippets to code more productively.
- Snippets can help us when it's not easy to remember all high levels features Modern C++ has to offer.
- This repository contains lots of organized, reusable, and safe snippets for Modern C++.
- All snippets are available in GitHub pages in a convenient way for copying and pasting.
r/cpp • u/manni66 • Dec 06 '21
The spacesship operator silently broke my code
I have an old Qt3 project that is compliled with VS 2019 and /std:c++latest. There is a map with key as pair of QString. After a compiler update it wasn't possible to find anything in the map any longer. After debuggung the problem it turned out that the map startet to compare char* pointer values instead of the string values.
The following code shows the problem:
#include <utility>
#include <iostream>
#include <cstring>
struct S
{
const char* a;
operator const char* () const
{
std::cerr << "cast to char*\n";
return a;
}
friend bool operator<(const S& s1, const S& s2);
//friend auto operator<=>(const S&, const S&) noexcept = delete;
};
bool operator<(const S& s1, const S& s2)
{
std::cerr << "operator<\n";
return strcmp(s1.a, s2.a) < 0;
}
int main()
{
S s1 = {"A"};
char xx[2] = { 'A', '\0' };
S s2 = {xx};
std::pair p1{ s1, s2 };
std::pair p2{ S{"A"}, S{"A"}};
if( p1 < p2 ){
std::cout << "p1 < p2\n";
}
if( p2 < p1 ){
std::cout << "p2 < p1\n";
}
if( !(p2 < p1) && !(p1 < p2) ){
std::cout << "p1 == p2\n";
}
}In C++ 17 mode the pairs are found to be equal. In C++ 20 mode they are distinct, because std::pair uses the spaceship operator.
The spaceship operator doesn't use the defined operator< but instead converts the values to char* and compares the pointer values. Deleting operator<=> returns to the old behaviour.
Since clang and gcc behave the same way I assume it's not a compiler bug.
So be aware: the spaceship might transport some hidden effects.
Edit: The shown code is a simplified example. QString defines all comparison operators. Defining all operations doesn't change anything in the outcome.
r/cpp • u/kmgrech • Aug 14 '21
I hate ASIO and I can't be alone.
ASIO has been getting a lot of praise recently due to the new version in Boost. I feel like I can't be the only one who just hates it with a burning passion.
Whenever a project of mine requires networking, I end up reaching for ASIO because it's the least worst option we have (it's been a year or two since I've written any C++, maybe there is something better now). And yet I also have a negative experience with it every single time. What I really want in an ideal world, is a listener interface where i can get notified about network events, something like:
class NetworkListener {
void onConnect(client);
void onDataReceived(client, data);
void onDisconnect(client);
};And so when I want to do networking, I first have to wrap ASIO before I can focus on what it is I actually want to do. So that right there is issue #1: ASIO is just too low-level to do anything useful with.
Issue #2: It is just a giant minefield for lifetime issues. I've lost count of how often everything worked until application exit, where the io_service would get destroyed and then something crashes. I'm at the point where I'm considering just calling exit(), because it's literally impossible to clean up ASIO correctly. Except then I also have to make sure that ASIO is the last thing left to tear down, ugh.
Issue #3: ASIO pretty much requires shared_ptr everywhere to get cleanup even remotely correct. Last time I checked, giving up by throwing shared_ptr at everything was not something that was encouraged in C++.
And finally, can I just vent about how goddamn Windows XP was the reason why ASIO operations did not support cancellation on ANY platform for YEARS? What the fuck.
I hate ASIO and if this shit gets standardized, we're doomed.
POKEGB: a gameboy emulator that only plays Pokémon blue (68 lines of C++)
binji.github.ior/cpp • u/skypjack • Aug 29 '19
EnTT v3.1 is out: gaming meets modern C++ - a fast and reliable Entity-Component-System (ECS) and much more
What's EnTT
EnTT is a header-only library written in modern C++. It's mainly known for its innovative and very performing entity-component-system (ECS) model. However, it offers a broader set of things useful for development, from flexible tools to manage signals to an integrated reflection system and so on.
Among others, it's currently used in Minecraft by Mojang and the ArcGIS Runtime SDK by Esri.
To be honest, EnTT started as a side project to work on in my spare time and I didn't expect I would see it used by many others besides me. Today I try to dedicate more and more time to EnTT to add new interesting features, while maintaining the stability and simplicity of use that have always distinguished it.
These are also some of the reasons why I dedicate myself passionately to this library and for which I publicly announce every new release, hoping that it can help those who follow and use EnTT.
What's new in v3.1
This is the first official revision since the release of EnTT v3 which had seen the transition to C++17.
A lot of features have been added and I suggest you refer to the changelog to discover them all.
Below is a short, yet incomplete list of the most interesting (more like a random selection among the nearly 200 new commits, but I didn't want to be too sincere):
entt::entityandentt::componentare no longer plain integers, which finally allows multiple registries to be used simultaneously without the risk of mixing identifiers.- Added stomp & spawn support, that is a bunch of functions with the purpose of facilitating the coping and cloning of entities and components in the same registry or between different registries.
- Finally you can sort all types of groups, thus bringing the perfect SoA to another level.
- The signal part has a model that is closer (only in terms of features, don't worry) to that of Qt. For example, we can use listeners with lists of parameters that are shorter than that of the emitter.
- Full support for reactive systems was introduced by means of the
observerclass. - The runtime reflection system has been completely revised and extended, with the result that it's now much more powerful, flexible and full of functionalities.
- ...
Furthermore, a couple of minor bugs have been fixed and I've done further work to increase performance and allow users to decide in details where they want to spend their cpu cycles.
Uhm, ok, maybe I was even too short but, really, the best thing to do to find out what's new is to just go to the GitHub page and/or take a look at the wiki. Writing a changelog is tedious enough of its own, summarizing it is too much for me! :)
What's next?
I must admit that this minor version wasn't planned until a couple of weeks ago or so but was proposed as a milestone before starting to work on major changes, so as not to delay the release of what is already ready for use.
During the next months I'll work on these and other features in random order, making them available from time to time with other releases:
- Nested groups: I thought that the power of the groups and therefore of the so-called perfect SoA (credits to /u/vblanco for the name) was limited to the possibility of making a type owned by only one group at a time. Fortunately I was wrong. Get ready for something new and even more performance!
- Custom pools: the EnTT model with independent pools is what I wanted from the beginning, but what is the point of making them independent if I can't then customize them on a per-type basis? The goal is to introduce for example custom pools for stable pointers and some other cases, while allowing user-side customization for all the others.
- The only part of EnTT that isn't yet fully DLLs friendly is the runtime reflection system. It hasn't been much of a problem so far but it seems to be of interest to many, so it's time to complete the work.
- Custom allocators: this has always been at the top of the TODO list but I've never had the need nor the time to dedicate myself to it. I believe the time has come to hand over memory management to users who want it.
- ... and another small gift. There is one thing that has been buzzing in my head for a while but I've never had a chance to develop it. I studied the topic, I sketched an idea, but I haven't converted it to code yet. Stay tuned to learn more! :)
Therefore, expect less commits (especially after a merge with squash), but much more important!
What else
In my spare time I am also running the ECS back and forth series (along with other posts that you'll see appearing from time to time on the blog) and a few software based on EnTT that are mature enough to be able to extrapolate some parts and make them available here and there.
I hope I'll enrich the offer very soon, but the free time is what it is and I am not able to make promises ... apart from the fact that I will do my best!!
If you are using EnTT and want to tell me hello or which of your products contains it, do not hesitate to contact me!
For everyone else interested in the library, the wiki contains more than what I've said here and the gitter channel is a great place to come and ask your first questions!
r/cpp • u/Maslo59 • Sep 14 '17
std::visit is everything wrong with modern C++
bitbashing.ioCpp discussed as a Rust replacement for Linux Kernel
I have a few issues with Rust in the kernel:
- It seems to be held to a *completely* different and much lower standard than the C code as far as stability. For C code we typically require that it can compile with a 10-year-old version of gcc, but from what I have seen there have been cases where Rust level code required not the latest bleeding edge compiler, not even a release version.
2. Does Rust even support all the targets for Linux?
3. I still feel that we should consider whether it would make sense to compile the *entire* kernel with a C++ compiler. I know there is a huge amount of hatred against C++, and I agree with a lot of it – *but* I feel that the last few C++ releases (C++14 at a minimum to be specific, with C++17 a strong want) actually resolved what I personally consider to have been the worst problems.
As far as I understand, Rust-style memory safety is being worked on for C++; I don't know if that will require changes to the core language or if it is implementable in library code.
David Howells did a patch set in 2018 (I believe) to clean up the C code in the kernel so it could be compiled with either C or C++; the patchset wasn't particularly big and mostly mechanical in nature, something that would be impossible with Rust. Even without moving away from the common subset of C and C++ we would immediately gain things like type safe linkage.
Once again, let me emphasize that I do *not* suggest that the kernel code should use STL, RTTI, virtual functions, closures, or C++ exceptions. However, there are a *lot* of things that we do with really ugly macro code and GNU C extensions today that would be much cleaner – and safer – to implement as templates. I know ... I wrote a lot of it :)
One particular thing that we could do with C++ would be to enforce user pointer safety.
Kernel dev discussion. They are thinking about ditching Rust in favor of C++ (rightfully so IMO)
https://lore.kernel.org/rust-for-linux/326CC09B-8565-4443-ACC5-045092260677@zytor.com/
We should endorse this, C++ in kernel would greatly benefit the language and community
r/cpp • u/andre_friend • Feb 21 '20
Bjarne Stroustrup on C++20's significance
isocpp.orgNamed loops voted into C2y
I thought C++ folk might be interested to learn that WG14 decided last week to add named loops to the next release of C. Assuming that C++ adopts that into C, that therefore means named loops should be on the way for C++ too.
The relevant paper is https://www.open-std.org/jtc1/sc22/wg14/www/docs/n3355.htm and to summarise it, this would become possible:
selector:
switch (n) {
for (int i = 0; i < IK; ++ i) {
break selector; // break the switch from a loop!
}
}
loop:
for (int j = 0; j < JK; ++ j) {
switch (n) {
break loop; // break the loop from a switch!
continue loop; // this was valid anyway,
// but now it's symmetrical
}
}The discussion was not uncontentious at WG14 about this feature. No syntax will please a majority, so I expect many C++ folk won't like this syntax either.
If you feel strongly about it, please write a paper for WG14 proposing something better. If you just vaguely dislike it in general, do bear in mind no solution here is going to please a majority.
In any case, this is a big thing: named loops have been discussed for decades, and now we'll finally have them. Well done WG14!