/r/cpp
Discussions, articles and news about the C++ programming language or programming in C++.
Discussions, articles, and news about the C++ programming language or programming in C++.
For C++ questions, answers, help, and advice see r/cpp_questions or StackOverflow.
Get Started
The C++ Standard Home has a nice getting started page.
Videos
The C++ standard committee's education study group has a nice list of recommended videos.
Reference
Books
There is a useful list of books on Stack Overflow. In most cases reading a book is the best way to learn C++.
/r/cpp
Optimizing clang has been shown to have significant benefits for compile times. However, the version mentioned in that issue has been trained on builds of the Linux kernel, which means it doesn't have optimization for C++-specific code paths. Building clang with these optimizations is not trivial for every dev to do themselves (error-prone and takes about 4 clean builds of clang). So I'm wondering, does anyone know of pre-built versions of clang or gcc out there that are PGO/BOLT optimized with a training set that includes C++ builds?
For Qt developers out there, I see a lot of people talking about how Qt is the go-to GUI framework for C++, but I would like to know: is it common to use it with Visual Studio? Let's say you have a pre-existing code base and you want to migrate the GUI framework from MFC to Qt. Do you have to use Qt Creator? Can you reasonably integrate the library into your code base in Visual Studio?
It's probably possible, as anything in tech, but my question is: is it common or reasonable to do that?
This Reddit post will now be a roundup of any new news from upcoming conferences with then the full list now being available at https://programmingarchive.com/upcoming-conference-news/
Imagine I decided that because boost::regex
is better I do not want to use std::regex
.
I can not try this out since there is no modular boost, but here is hypothetical example:
import std;
import boost.regex;
using namespace std;
using namespace boost;
// use std:: stuff here, but not regex
// ...
//
int main() {
regex re{"A.*RGH"}; // ambiguous
}
With headers this is easier, if I do not include <regex>
this will work fine(assuming none of my transitive headers include it).
I know many will just suggest typing std::
, that is not the point of my question.
But if you must know 😉 I almost never do using namespace X
, I mostly do aliases.
Recently came across this video which showcases an amazing UI layout library written in C which can be used in C and C++ to create amazing UIs. The only thing that concerned me is the format of code due to heavy use of macros. I feel for large applications, it can become difficult to navigate.
Does any library like this exist which is made with modern C++?
/* I am sorry this is off topic for c++ but it's the point of my post. Mods, this could help people looking for the same and keeping your subreddit on topic */
There have been many times I want to discuss topics related to programming but don't have luck in a place like r/programming. I really enjoy the signal to noise ratio of this sub but I don't have a lot of C++ to talk about. If i want to discuss general industry topics, I try to figure out a way to relate it to c++ because I feel the responses here are generally better. but usually I just let it go.
So I am hoping some people here have some not well-known generalist subreddits where the quality of discussion is better.
I wanted to do simple experiment:
if
with many ==
std::array
and std:ranges::find
to see if there is overhead or compiler figures it all out.Story turned out to be more interesting that I expected. If you are just looking for godbolt enjoy, text bellow is my recap.
As introduction these are 3 ways to do same thing(one notable thing is that values are small integral values, it matters later):
[[gnu::noinline]]
bool contains0(int val) {
return (val == 10 || val == 11 || val == 42 || val == 49);
}
[[gnu::noinline]]
bool contains1(int val) {
if (val == 10 || val == 11 || val == 42 || val == 49) {
return true;
} else {
return false;
}
}
[[gnu::noinline]]
bool contains2(int val) {
static constexpr std::array vals{10, 11, 42, 49};
return std::ranges::find(vals, val) != vals.end();
}
(╯°□°)╯︵ ┻━┻
moment was seeing clang compile contains0
and contains1
differently.
Then we move to contains2
asm, to see if compilers can see through abstraction of std::array and std::ranges
.
Here gcc has array represented as normal array and loads values from it to compare it with passed argument. clang did amazingly and compiled contains2
to:
contains2(int):
mov ecx, edi
cmp edi, 50
setb dl
movabs rax, 567347999935488
shr rax, cl
and al, dl
ret
567347999935488/0x2'0400'0000'0C00
is bitmask of values(if you remember I said it is important that values are small).
What is interesting is that this is same constant gcc uses for contains0
and contains1
while clang implements contains1
without this optimization although he does it for contains0
. So two compilers use same trick with bitmask of values, but only if you implement logic in different ways.
I hope nobody will extract any general opinions about quality of optimizations in different compilers from this simple example(I could change values, number of values, ...), but I hope it is still useful to see.
I for one have learned to check my assumptions if microoptimization matters, if you asked me before today if contains0
and contains1
compile to same asm I would sarcastically respond: "Yeah, like for past 20 years". 😀
edit: big thanks to comments, discussing different variations
I've finally realized why templates can be generic on both class
and typename
:
template< class These
typename Names
typename Align
>
(assuming an 8-wide indentation of course)
---
While I'm at it - C# has this interesting thing you can do with a switch:
switch(AddRed(),AddGreen(),AddBlue())
{
case (true ,true ,true ): return White;
case (true ,true ,false): return Yellow;
case (true ,false,true ): return Magenta;
case (true ,false,false): return Red;
case (false,true ,true ): return Cyan;
case (false,true ,false): return Green;
case (false,false,true ): return Blue;
case (false,false,false): return Black;
}
which we don't really have in C++ but you can get the same nicely aligned return values:
auto r = add_red();
auto g = add_green();
auto b = add_blue();
if(r) if(g) if(b) return white;
else return yellow;
else if(b) return magenta;
else return red;
else if(g) if(b) return cyan;
else return green;
else if(b) return blue;
else return black;
all I need now is a clang-format rule to enforce this
constexpr auto foo() {
static constexpr std::string a("0123456789abcde"); // ::size 15, completely fine
static constexpr std::string b("0123456789abcdef"); // ::size 16, mimimi heap allocation
return a.size() + b.size();
}
int main() {
constexpr auto bar = foo();
std::cout << "bar: " << bar << std::endl;
}
This will not compile with clang-18.1.8 and c++20 unless you remove the 'f' in line 3. What?
I've pursued C++ software path for an amount of time. Now I have gained a certain skill in C++, system design, DSA, multithreading, OOAD,...
I just wonder if I have to learn additional skills or complete more projects and gain enough experience to gain senior level? Btw, Could you share your own path to becoming a senior C++ software engineer?
https://github.com/llvm/llvm-project/pull/117673
It's in main so if you have a package repository with the latest llvm you can update clangd-20 and try it out.
Debian:
apt install clangd-20
You may have to set your IDE settings to specifically call clangd-20
In VSCode:
{ ... "settings": { ... "clangd.path": "clangd-20",
https://marketplace.visualstudio.com/items?itemName=llvm-vs-code-extensions.vscode-clangd
In programming, why do we call unsigned values "unsigned ints" or "uints"?
Integers are signed by definition. It's a contradiction in terms.
Unsigned values are called the naturals.
Why don't we call them "nats"?
I've added these definitions to my stdfelice.h header, where I fix stuff in C/C++ that I disagree with:
// Edit: I realize in C++ these should be using `using` instead
// of `typedef`, but my .h file is intended for both C and C++ and
// C does not support `using`.
typedef unsigned int nat;
typedef uint8_t nat8_t;
typedef uint16_t nat16_t;
typedef uint32_t nat32_t;
typedef uint64_t nat64_t;
typedef uintptr_t natptr_t;
#define NAT_MAX UINT_MAX
This has the upside that the labels are the same char width as ints! No more ugly unaligned code with mixed signage!
Common points being raised:
Point: An unsigned int doesn't cover the entire range of naturals, so shouldn't that make it an unsuitable term?
Response: An int doesn't cover the entire range of integers, but we still call it an int for pragmatic reasons, i.e. it's the closest fit. I think nat(ural) can be used likewise.
Point: But in my country/culture/language (Germany and Russia were mentioned) we don't consider naturals to include 0, so that doesn't work for me.
Response: As far as I could tell from the research I did while coming up with this idea, the English-speaking world generally agrees that natural numbers include 0. I realize this may conflict with other cultures, but there's already a lot of ethnocentricity in programming languages created in the west, so I feel like it's kind of a drop in the bucket, really. But still a fair point from the speaker's point of view. Not sure what else to say here.
A follow-up regarding my motives and intentions: I do NOT expect the community to suddenly say "omg you're right" and rally to change the C/C++ standard. I just wanted to see what other people thought about this and whether or not it could make sense to people other than me. I mean, if I plant a seed that, in 50 years, means that in C++74 we have native nat
types, that's great, but I'm really just sharing my thoughts here and wondering what other people think.
Perhaps I should ask, "If this were a new language and it called this type of number nat
, and you understood what I've explained so far, would it be acceptable? Would it make enough sense that you'd go with the flow, or would you complain bitterly that you had to use nat
instead of the uint
you were used to? Would you just typedef a uint
out of spite for the language's idiot creator?"
Edit: Please just ignore this aside, it's really not germane and I don't want to derail the nat talk. I'd delete it outright but it always seems sketchy when people delete stuff they've written and I don't like to do that.
(As an aside, I also define flt, flt32_t and flt64_t, purely for cosmetic reasons. This is not something I would argue for, though. I'm just mentioning it in passing in case anyone else who's OCD about stuff like function argument lists lining up is interested.)
CppCon
2024-12-09 - 2024-12-15
2024-12-02 - 2024-12-08
2024-11-25 - 2024-12-01
C++OnSea
2024-12-09 - 2024-12-15
2024-12-02 - 2024-12-08
2024-11-25 - 2024-12-01
ACCU Conference
2024-12-09 - 2024-12-15
2024-12-02 - 2024-12-08
2024-11-25 - 2024-12-01
CppNorth
2024-12-09 - 2024-12-15
2024-12-02 - 2024-12-08
2024-11-25 - 2024-12-01
TL;DR: My IDE is suggesting I mark my class constructor as explicit and I am trying to understand the concept behind it and whether or not it's relevant in a small college project I am doing for my data structures class in C++.
I have been trying to read the documentation and even tried having GPT explain it to me so I will give you context of what I am working on and maybe you can help me understand:
For college, we are working on a project in which we create a database. We are using C++ so we can become familiar with low level programming and how relational databases work, etc.. For context, the database will store serial numbers, item descriptions and price points among other details. I was building a simple rows/columns class and my clang-tidy threw back this:
Clang-Tidy: Single-argument constructors must be marked explicit to avoid unintentional implicit conversions
It was just a yellow warning but I was curious as to what it meant so I looked into it and it seems to be suggested for me to use explicit
to prevent the possibility of unintended values being passed into the class constructor. So by adding explicit
I would then have to call the constructor as such:
rows r(value);
vs rows r = value;
Based on the fact that I don't see the relevance in my program I have come to two conclusions:
I tried asking GPT to give me examples in which it would be relevant and the analogies it used maybe were not clicking or I am too new to the language to understand the importance of this yet. Currently my program is not misbehaving, but I would want to understand the concept of explicit.
I am hoping someone can explain in not overly complicated terms or maybe in an analogy that might be more relevant to me as I can't seem to grasp this on my own.
Hey guys, So It's nearly 2025 and C++ reflection is still not out..
But we also hear: some developers are using c++ reflection now via: 'various means'.
I thought I'd share how I do it, and maybe show some of the things I've been using it for:
https://imgur.com/a/programs-i-created-which-use-c-code-reflection-WuwtqYl
Custom linting, styling, optimizing, advanced navigation, drag/drop code-editing tools, general transformations, all easier than you'd think once you have reliable reflection.
Now that you're all excited and pumped up!, here comes the cold water:
Note: While the technique below does provide 100% functional code reflection; implementing it in this-way may not be appropriate for all projects.
By which I mean If you want to do it this way: you'll need to include an xml reader with your program and doxygen (I just keep doxygen in assets as a third-party exe)
Okay lets get started: At The Top Of This Page : https://www.doxygen.nl/manual/customize.html You'll Find -
"Doxygen provides various levels of customization... The section XML output shows how to generate whatever output you want based on the XML output produced by Doxygen."
I let it dump everything in XML mode, Then I use simple Object Orientated code to read and hold The XML data : https://imgur.com/a/RIQU4iq
With a system like this, you can target a file and get back a 'CodeFile' object, containing includes, classes, etc, those classes are objects aswell, containing others representations for reflections of functions, member variables etc, when you want to reflect on your own code, you just iterate thru these objects (also Yes hehe I did try having code.h target itself!, and yes the results are extremely confusing when you do that! haha)
That's about it it really is that sample, takes probably a day or two for a good programmer and your off, just point your system at some c++ code, and learn everything about what's going on ;)
How to use reflection to make cool things is a whole different story, but happy to go into details in comments..
Thanks!
Note: Love to hear if anyone else has interesting ideas or techniques in this area (edit: jaskij has pointed out you can optionally swap between using doxygens-xml or clang's -ast-dump) also happy to share details or code snippets for anyone curious about any of my tools which use code reflection.
Note: Not the perfect reflection solution for everyone I know, (perhaps embedded devs etc might have issues), but for people with big awesome code bases, who are not really held back by anything, and who just want to have godly insight into and control over their own code base - no need to wait - c++ reflection is here now and works nicely
Enjoy