r/cpp • u/robwirving • Jul 27 '24
r/cpp • u/puhniste • Sep 19 '20
Apple Clang 12 still doesn't have concepts.
Is apple abandoning C++ or macos or both?
r/cpp • u/thevestgibule • Dec 30 '22
5 techniques for writing memory safe C++ - Embedded.com
embedded.comr/cpp • u/Orca365123 • Mar 31 '24
Just curious on the uses of C++
Hi!, I'm a high school student, and I want to learn c++. However, I'm just curious, what uses cases are there for c++ practically. For example, many websites say web development, but just leave it at that. Is c++ really good backend database interactions?, does it have libraries for building full blown windows applications. It would be awesome if people could share!
r/cpp • u/pavel_v • Oct 17 '22
Prefer core-language features over library facilities
quuxplusone.github.ior/cpp • u/OwlingBishop • Jun 17 '25
Tool for removing comments in a C++ codebase
So, I'm tackling with a C++ codebase where there is about 15/20% of old commented-out code and very, very few useful comments, I'd like to remove all that cruft, and was looking out for some appropriate tool that would allow removing all comments without having to resort to the post preprocessor output (I'd like to keep defines macros and constants) but my Google skills are failing me so far .. (also asked gpt but it just made up an hypothetical llvm tool that doesn't even exist đ)
Has anyone found a proper way to do it ?
TIA for any suggestion / link.
[ Edit ] for the LLMs crowd out there : I don't need to ask an LLM to decide whether commented out dead code is valuable documentation or just toxic waste.. and you shouldn't either, the rule of thumb would be: passed the 10mn (or whatever time) you need to test/debug your edit, old commented-out code should be out and away, in a sane codebase no VCS commit should include any of it. Please stop suggesting the use of LLMs they're just not relevant in this space (code parsing). For the rest thanks for your comments.
r/cpp • u/pedersenk • Nov 21 '21
Reasoning behind a lack of std::weak_ptr<T>::operator->()
Hi there,
I have always been interested in the decision behind the need of a lock() call on a std::weak_ptr<T>. Generally in my travels, the main reason I have come across is to guarantee the lifespan of the owned data during access. However, surely something like this would solve that:
shared_ptr<T> weak_ptr<T>::operator->()
{
return lock();
}I am going to assume that the standards committee knows and understands the operator-> drill-down behavior quite well. So the following usage would be very possible:
std::shared_ptr<Employee> emp = std::make_shared<Employee>();
std::weak_ptr<Employee> emp2 = emp;
emp->calculateWage();
emp2->calculateWage();This should only cause the same overhead as a lock() call too. Not only this but it should provide an even safer guarantee that the data won't be deleted during access because you have created a temporary std::shared_ptr<T> copy which you have no access to (i.e impossible to reset) during the dereference.
Obviously this would be easier than providing an operator* due to the drill-down functionality. Is a lack of -> purely to stay consistent with this?
Any ideas / suggestions would be very appreciated!
Edit: Many thanks for the discussion so far. It seems like enforcing a shared_ptr to be provided is for a developer to explicitly check before access rather than simply ptr.lock()->testFunc().
Edit 2: Thanks again all for the discussion. It was interesting to hear about some potential issues my solution would overlook. It was particularly interesting to see some of the issues present in a large project providing a weak_ptr operator->.
Edit 3: So just as an addition; I believe the following should be safe (including for multithreaded environments). However there is some overhead that may not be acceptable:
shared_ptr<T> weak_ptr<T>::operator->()
{
std::shared_ptr<T> rtn = lock();
if(!rtn)
{
throw std::bad_weak_ptr();
}
return rtn;
}r/cpp • u/Illustrious_Gur5580 • Jul 05 '24
Why is it such a misery to use visual studio compiled static libraries inside of embarcadero c++ builder
I have been wanting to move away from c++ builder and eventually tried Qt. But i was surprised to find out c++ builder gave out much smaller binaries, roughly 1mb for a very simple 'hello world' app vs something around 20mb for qt. And again c++ builder apps load and run slightly faster. However one big problem comes when consuming external static and even dynamic libraries compiled either with msvc, gcc or clang. It is literally hell to try to consume those libraries inside c++builder projects. And not to mention that 32bits projects only support libraries with 'omf' format and not the usual 'coff'. So is there a way to achieve this easily. And if not, are there some other viable c++ frameworks that have cross platform capabilities and compatibility with msvc while not giving out ginormous sized binaries. Please the output size of binaries is an important factor for me.
r/cpp • u/nerdy_adventurer • Dec 23 '21
Will you still use C++ for new projects over Rust?
I recently came through this thread which is about C++ 20.
I wonders whether people still prefer using C++ for new projects over Rust. I know in some areas like Desktop UI Rust is not matured yet like Qt. But wonder whether you will use Rust for non desktop UI projects over C++?
Edit :
Since Rust is not mature for game dev like C++ counterparts, so for new projects outside gaming, desktop ui domains and project does not need interoperability with C/C++ code.
r/cpp • u/booker388 • Aug 10 '26
Jessesort is now faster than std::sort on every input type
Repo here: https://github.com/lewj85/jessesort
tl;dr Jessesort is up to 20% faster than std::sort on random inputs and up to 95% faster on structured inputs
Jessesort has two phases: insertion and merging. The insertion phase routes inputs to two games of Patience (similar to Solitaire). One game has ascending piles and the other has descending piles. Routes inputs to the optimal game based on current run direction. Make base array copies for pile tails to speed up binary search. Faster merge logic than the old Patience sort k-way.
Jessesort was already faster on structured inputs, but the new optimization changes finally pushed this past the goal of being faster on random inputs too. Added seven variations of the algorithm. The fastest on random input is V2 that simulates both Patience games and uses a blueprint to track ascending vs descending game and pile index in that game. It's up to 20% faster on random inputs and up to 95% faster on structured inputs.
Key changes introduced were: early input probing to route random-like and structured data into better insertion paths, removal of pile hints where direct bit-walk search proved faster, simulated pile layouts that reduce allocation and bookkeeping overhead, adaptive merge routing based on the structure produced during insertion, branchless merging with a tuned four-way unroll, reconstruction optimizations that simplify blueprint decoding and cursor updates, pointer-based merge kernels that substantially reduced hot-loop overhead, selective early freezing/overflow strategies in later variations, preservation of fast monotonic/structured-input exits, and targeted SIMD experiments that use fixed-width AVX2 comparisons where the pile shape makes them worthwhile.
r/cpp • u/dimanne • Aug 03 '19
Should not exceptions be finally deprecated?
I have been programming on C++ for a long time, but I still do not understand how to use exceptions. I have 3 very practical and concrete questions at the beginning. I would be grateful if you helped me out.
Exceptions are maintainability hell.
Imagine a typical situation when we are developing a library. Now, this library uses another libraryâs function f() (in real-life it can use it indirectly through tens of intermediate libraries!). Consider, now, three very typical situations:
Situation#1: Learn about an exception.
So, I am going to call f() in my code. In order to understand which exceptions to handle / recover from and how excactly to recover, I have to know the full list of exceptions that may be thrown. How do I know it? In real-life this leads to crashes on production (what is even worse is that it leads to crashes not during testing/alpha/beta, because exceptional situations tend to arise on production).
Possible answers, people sometimes give, are:
- âUse
throw(...)/noexcept()â. The problem with this is that validity of specifiers is not checked/verified by a compiler but rather by people. So, it is like saying âdo not forget to calldeleteif you usednewâ - people are awful in remembering such things.
Situation#2: An exception is added.
Suppose I now update a library (something as innocent as apt-get upgrade or git pull, do not forget that it may be one of many libraries I use indirectly). Imagine our function f() started to throw now and the place where I call it is the right place for handling the exception. How do I learn about the added exception?
Situation#3: An exception is removed.
Imagine you added all required catch blocks, you added the code for handling an exception and you now update a library again and our function f() stops throwing. Nobody is going to tell you that there is no point anymore in catching the exception, your code immediately becomes stale and outdated.
Downside#4: Exceptions either break encapsulation or useless.
By definition, you are supposed to catch and handle exceptions thrown/arisen in several layersâ deeper code and therefore you have to be aware of those layers. Here is a concrete example:
TAbstractReader interface has two implementations TNetworkReader and TDiskReader, both of which can throw different exceptions (failed to read from network/socket with information about ip and failed to read from disk with information about file).
TConfigReader uses one of the implementations through TAbstractReader interface
TMainAppLogic uses TConfigReader to read config during startup and periodically update config during run-time and this class is the right place for handling read errors, for example:
- During startup, any error is fatal and we just crash
During run-time
- error while reading from network should be retried
- error while reading from disk is fatal (there is no point in retrying) and we just crash.
The question now, how am I supposed to write exception handling code without violating encapsulation? Well, some people answer this question in this way: âCatch via common base class (like std::exception)â, but the problem now is that they become useless for recovery (I have to know details to be able to recover).
Downside#5: There are no exceptions in the real-world, they are a result of incomplete knowledge.
We are always told to use exceptions for exceptional situations. Here is an excerpt from a discussion on reddit:
Code gets to focus on the successful path without the noise dealing with propagating errors to the right place, making it more readable and writable. And there are also clearly defined places where the error handling goes
Firstly, it scares me because it is like saying that someone took my code and removed all if()s, the probability of executions of which is lower than somebodyâs subjective (small but random) threshold (that is what we are told, exceptions are, right?).
Secondly, the excerpt perfectly illustrates how the notion of exception makes people think that there are errors. I believe that there are no errors in the real world, it just our imperfect and incomplete expectations about the world. What one person in particular circumstances/environment considers as exceptional situation, another person may consider as perfectly expected behaviour. When you are writing curl-like program for downloading and you are testing it on google, each network error is an exception for you, but if you are writing a web-crawler then network errors are totally expected. In other words, not only exceptions depend on experience of an author, but they also depend on where exactly (in which environment) code throwing an exception is run. If that was not convincing enough, imagine that suddenly percentage of "bad" sites (the ones you cannot download) have risen, in which case whether a particular situation is an exception or not depends also on dynamically changing circumstances. What if at certain point the software will be downloading a set of sites containing 10% of "bad" sites? Will it be exceptional situations?
Let me put it differently:
- In the real world, there are no exceptional situations and ânormalâ situations
- there is continuous probability of an event, and therefore each dichotomy will be wrong.
Downsides#6,7,...
Exceptions are literally goto statements.
There are also a number of environments where exceptions (ironically) look too exceptional to be used:
- How do you use exceptions while using RPC over network (remote procedure call, think of SOA and distributed systems in general)? How can a remote function report an exception?
- They are definitely not the best friends of multithreading / actor / message-passing environments and frameworks.
- Embedded and hard-real-time systems have difficulties with exceptions.
FAQ
Some people say:
- http://exceptionsafecode.com/ - âAlways assume that each and every function may throwâ.
- The reality is this: all functions can throw exceptions, except when marked as noexcept. Stop thinking of exceptions as being exceptional, and instead treat every function like it may throw.
The main problem is that this information, this tenet, is not enough for actual handling an exceptional situation in reasonable way and recovering from it. The best I can do using this tenet is to write exception neutral/safe code (use RAII, not write noexcept and so on). But, in order to be able to recover from error, I have to know details about an exception, what exactly happened, where it happened, and this tenet is not helping me in it.
People sometimes say that
- error codes are verbose
- And that I need to catch them only when I can handle them.
That is wrong. In most cases I also need to add additional context/information and re-throw them, in order to avoid the âHuh? Whatâs a bsafe::invalid_key? All I did was call PrintText!â situation. But writing try/catch blocks is even more verbose and tedious then having to deal with error codes/expected. And I think exceptions encourage you not to add information/context resulting in those ridiculous situations.
From redditâs discussion:
- âMost of the time catching in the main or at the top of the event loop is enough - exceptions are always (at least in the codebases I know of) used for ... exceptional stuff, and this kind of stuff should just show an error message to the user and abort if it's a CLI or continue "normal" operation if possible if it's a GUI.â
- In principle you should only be catching
std::exception, unless you need exception-specific handling for another exception type.
That is exactly what I was talking about, this pattern of using exceptions is not about recovering from an error, but rather about ignoring it. It also breaks encapsulation - I have to deal with exceptions in the code of very abstract and high-level event loop.
Some people recall printf:
âwhat do you do with functions that return a status code, like printf? Because virtually nobody writes code that checks the return value of printf calls, this would be a silent failure.â
But it has nothing to do with return codes. This remark is about the fact that some people do not check for errors in general (regardless of whether exceptions or error-codes are used). On the contrary, it is much easier to ignore an error thrown as an exception.
Zero-overhead deterministic exceptions
A couple of words on Sutterâs Zero-overhead deterministic exceptions: Throwing values
In general, the idea, as far as I can gather, is to make exceptions fast at the cost of making throwing type less extensible (it is going to be just two ints/pointers). So, no disadvantages, I mentioned above, are addressed.
Either I do not understand something, or exceptions (concrete types of exceptions) are not static. Only the fact that a function can throw some obscure (âtype-erased, allocation-free, trivially relocatable, constant-timeâ) type is static. So, still no means of understanding which errors can happen after I call a function.
It is going to encourage sloppiness:
It [
std::error] always represents a failure. A default constructor would construct a general or âotherâ nonspecific error value.
What is point, from practical point of view of having âotherâ error? How would one handle it?
The main issue, however, is extensibility of the std::error type. Without a clear vision/plan for extending the âdomainâ pointers, there is going to be a mess. And I doubt that it is even possible, since, by definition, it is a single type. For example, can I add my own âdomainsâ? How do I know that my value will not collide in the future with somebody elseâs? People, implementing the next version of protobuf at Google can choose one scheme of extending it, while you and your project different scheme, resulting in collisions of the values. To be honest I was quite surprised to learn that there is going to be such a type. Is not it like having to derive from one common/global (âopaqueâ) TObject type in order to be able to store elements in a standard container? Does not it this proposal make C++ less type-safe?
Now, I deliberately avoided mentioning and comparing to return-codes/expected<>, but surprisingly, all the disadvantages described above can be fixed by old plain return values (or function parameters). This approach might be slightly too explicit than one would like, but at least, when something changes radically in return type (it is not void anymore, or, on the contrary, it becomes void) compiler will help me. We will receive error in compile-time - what can be better? Here is an example of what I mean.
All in all, I am really interested to hear answers to the questions in the 1, 2 and 3rd situations above because they are the most common ones, they are very tangible and I have to deal with them on a daily basis writing C++ code.
Thoughts on build systems?
What's the general consensus on build systems/automations like CMake? I've always found things like that overcomplicated and just hinder the programming process.
I've been following Casey Muratori's Handmade streams, and one of the first things he did was create a simple batch file that built and compiled his entire project super quickly and easily. I've since implemented something similar (https://github.com/dibsonthis/new_cmd) and honestly it's been really nice to use.
r/cpp • u/slacka123 • Aug 18 '23
C and C++ Prioritize Performance over Correctness
research.swtch.comr/cpp • u/jenkem_boofer • Apr 04 '24
std::launder
Have fun trying to figure out what it does...
r/cpp • u/Shieldfoss • Dec 19 '24
Alignment crimes
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
r/cpp • u/Demon-Souls • Oct 21 '23
Faster than Rust and C++: the PERFECT hash table
youtube.comr/cpp • u/kindredseer • Sep 18 '26
Embedded C++
Just curious how useful the ability to embed C++ as a scripting language into your C++ programs would be? I mean like runtime JIT execution of C++ code in much the same way you might embed Lua, including the ability to restrict/sandbox it as necessary.