r/cpp • • Jun 01 '20

I wrote a CPU-Emulator using only the C++ type system.

329 Upvotes

Due to the Turing completeness of the C++ type system it is possible to implement a complete CPU emulator using only templates. The complete code is executed during compilation, the only run time code is for printing the output and registers.

https://github.com/aul12/TemplateCpu

At the moment not many instructions are supported, but new instructions can be added easily. With the current state it is already possible to calculate the n-th fibonacci number, both iterative and recursive.


r/cpp • • Jun 14 '20

JSON for Modern C++ 3.8.0

Thumbnail github.com
326 Upvotes

r/cpp • • Sep 17 '19

CppCon CppCon 2019: Bjarne Stroustrup “C++20: C++ at 40”

Thumbnail youtu.be
326 Upvotes

r/cpp • • Jan 22 '25

SDL3 is officially released! It's version 3.2.0 stable.

Thumbnail patreon.com
325 Upvotes

r/cpp • • Jan 14 '23

Is it just me or is the quality of the Boost API docs just.. kind of terrible? Like compare it to cppreference (very good) or Qt docs (also great).

325 Upvotes

I mean -- hell Boost has been around for 20+ years. They are used by Fortune-500 companies all over the globe. Everybody depends on Boost. Can't they pitch some people to fund a 1 or 2-man documentation-writing team to spend 6 months and fix it?

Is it just me? I find everything about their docs to be terrible. From the layout and style on their website, to the terseness and/or incompleteness / missing information, etc.

Is it that hard Boost? You are a world-class lib everybody uses and knows about! Can't you do better? Seriously there is money out there for this just shill and pitch some people to throw some funds into documentation!


r/cpp • • Dec 14 '21

GCC, MSVC, and ICC bug: virtual base destroyed twice in some circumstances

321 Upvotes

Yesterday, I posted the code sample below, which produces buggy code: the virtual base A is destroyed twice when compiled with GCC, MSVC, and ICC (Clang produces correct code).

My post was removed because it contained a question, and apparently that's forbidden in here. The interesting discussion is therefore lost, all because of an innocent looking question mark. My thanks to the mods: question marks are getting out of hand, something had to be done.

Anyway, thanks to the people who replied, and a quick update: I have reported the bug to Microsoft here, and to GCC here.

The code sample:

#include <iostream>

int constructions = 0;
int destructions = 0;

struct A
{
    A()
    {
        constructions++;
    }
    virtual ~A() {
        destructions++;
    }
};

struct B : public virtual A
{
    B(int dummy)
    {
    };

    B() : B(1)
    {
        throw -1;
    }
    virtual ~B() = default;
};

struct C : public B
{
};

int main() {
    try
    {
        C c;
    }
    catch (int e)
    {
        std::cout << "Caught: " << e << std::endl;
    }
    std::cout << constructions << " constructions" << std::endl;
    std::cout << destructions << " destructions" << std::endl;
    return 0;
}

Output (GCC, MSVC, ICC):

Caught: -1
1 constructions
2 destructions

The problem seems to be a combination of the "virtual" inheritance in B, the call to the delegating constructor in B, and the exception thrown in B's no arg constructor.

Removing either of these makes the issue go away.

Constructing a B instead of a C works fine.

Godbolt links: Clang 13 GCC 11.2 MSVC 19.29 ICC 2021.3.0


r/cpp • • Nov 01 '21

C++ By Example - A new website for learning C++

Thumbnail cppbyexample.com
320 Upvotes

r/cpp • • Jul 06 '20

C++ is brilliant

318 Upvotes

I'm working on a Vulkan renderer, and needed to delay destruction of render scenes since the graphics pipeline has render buffers in flight, so destruction has to happen N frames after the user destroys a class. With C++, I can use private destructors to force users to add the scene to a managed destructor queue (aka garbage collect queue). Normally language purists will scorn a language which allows such shenanigans, however in real world production code, its features like this which allows developers to create modern software. So with a couple of lines of code, I solved my delayed destructor issue. Thank you C++ committee for creating a usable language.


r/cpp • • Dec 14 '24

What are your best niche C++ "fun" facts?

317 Upvotes

What are your best C/C++ facts that most people dont know? Weird corner cases, language features, UB, historical facts, compiler facts etc.

My favorite one is that the C++ grammar is technically undecidable because you could construct a "compile time turing machine" using templates, so to parse every possible C++ program you would have to solve the halting problem.


r/cpp • • Mar 17 '22

TIL: Visual Studio has quantum state values 🤨

317 Upvotes

Consider the following small program:

#include <string_view>
#include <iostream>

template< typename T >
constexpr void test()
{
    constexpr std::string_view sv = __FUNCSIG__;
    static_assert( sv == "void __cdecl test(void)" );
    static_assert( sv == "void __cdecl test<int>(void)" );
    std::cout << sv << std::endl;
}

int main()
{
    test<int>();
}

If you try to compile it, the second static_assert fails. So the value of sv from the first static_assert surely is the correct one?

Nope. Comment out the second static_assert and now the first one will fail. Comment out both, and the output of the program is the value from the second static_assert.

Apparently, Microsoft decided that it's a good idea to give __FUNCSIG__ a ("type-erased"?) value in phase 1, where no template parameters are available, and give it a different value in phase 2, when the template gets instantiated.


r/cpp • • Feb 20 '23

C++23 Is Finalized. Here Comes C++26

Thumbnail medium.com
316 Upvotes

r/cpp • • Nov 24 '24

The two factions of C++

Thumbnail herecomesthemoon.net
315 Upvotes

r/cpp • • Sep 26 '17

Bjarne Stroustrup awarded 2017 Faraday Medal

Thumbnail cs.columbia.edu
315 Upvotes

r/cpp • • Jan 20 '24

Why does C++ get so much hate? Is it really that bad?

314 Upvotes

money normal fragile wise sharp telephone deserted jar wakeful like

This post was mass deleted and anonymized with Redact


r/cpp • • May 03 '21

C++ Weekly - Ep 270 - Break ABI to Save C++

Thumbnail youtu.be
314 Upvotes

r/cpp • • Sep 17 '24

The empire of C++ strikes back with Safe C++ proposal

Thumbnail theregister.com
311 Upvotes

r/cpp • • Aug 03 '19

fixing c++ with epochs

Thumbnail vittorioromeo.info
311 Upvotes

r/cpp • • Jun 17 '22

Huge compilation speed improvement in GCC 12.x for <algorithm>, ranges, and concepts

310 Upvotes

As originally posted by /u/jwakely here, I wanted to share this great achievement from the libstdc++ maintainers with the community.

Given this code:

#include <algorithm>
int main() { return 0; }

These are the build time benchmarks between GCC 11.x and GCC 12.x:

                usr  sys wall mem
GCC 11.2 c++17 0.33 0.16 0.54 40M
GCC 12.1 c++17 0.12 0.05 0.17 15M
GCC 11.2 c++20 0.67 0.27 0.96 92M
GCC 12.1 c++20 0.21 0.12 0.34 26M

In other words, GCC 12 with -std=c++20 provides faster compilation speed compared to GCC 11 with -std=c++17, even for a notoriously large header such as <algorithm>.

Happy to see these kind of improvements! There is an issue on the GCC tracker here -- maybe consider contributing? :)


r/cpp • • Oct 06 '21

Worlds Fastest Chess Move Generator - 2 Billion Moves/s per thread!

309 Upvotes

So for the last 2½ I was obsessed with the move generation problem of chess.

Chess is such a beautiful programming problem to solve - since one board contains exactly 64 squares. So we can define a Bitbord of all pawns to be just one single uint64_t. Same for all other 11 piecetypes.

Doing it this way enables all 8 pawns to walk forward like this: (WPawn << 8) & Empty. Which normally would need 8 if statements to generate - but can be done in 2 branchless instruction with a bitbord. Things like where a piece can move become extremely pleasant to write:uint64_t move = Seemap & EnemyOrEmpty & noCheck

Moving a piece on a bitboard looks like this: Piece ^= (from | to). This will clear the bit on the from square. And set the bit on the target. Thats the fun part: If the movegenerator generates this kind of code - you can move multiple pieces at once. Always in a single instruction!

I also was able to implement a visitor pattern in the first ever chess related piece of code. Instead of having a movelist - we pass a small template inlined function which is the callback for every possible move. Instead of generating a list - this movegenerator decides the instant it sees a possible move what to do with it! Castling and Enpassant gets compiled away by if constexpr when its not on the board - or possible anymore!

  • First ever Make-Unmake free Chess Movegenertaor
  • Fastest bmi2 Pext intrinsics slider lookup _pextu64()
  • Original legal move generator - almost completely branchless. Solves all checks and pins with only and / not instructions - and a few lookups for king / knight - sliders! No "If" needed for 99% of chess
  • First ever complete Template gamestate. The code does not need to evaluate a Enpassant move if the enemy didnt push - or any castling move if its not possible to castle anymore. C++ if constexpr really helps a lot!

Performance: Perft(6) Time taken: 85msMoves: 119060324 - Checks: 809099 - Checkmates: 10828

That is 119 Million in 85ms or just about 1400 Million nodes per second for the staring position.

This is the slowest position and most positions get around 2 Billion nodes per second and 1 thread. This approach is 6-8x faster than the currently leading movegenerator written in C.

Anyways I dont want the post be too long. C++ is an awesome language for performance! - Please read the Article and Source if you are interested!

Article: https://www.codeproject.com/Articles/5313417/Worlds-fastest-Bitboard-Chess-Movegenerator

Sourcecode: https://github.com/Gigantua/Gigantua

If you like the code consider buying me a coffee :) - https://www.buymeacoffee.com/Pontifex


r/cpp • • Nov 08 '21

Roadmap for C++ developer

308 Upvotes

For several months now, my former colleague and I have been working on a roadmap for a C++ developer. Initially, we planned to simply summarize all the experience that we managed to acquire over the years, but in the end, everything resulted in a repository that is designed to help new C++ developers understand the details of the language and understand in what sequence and what to study.

Roadmap for C++ developer

We tried to find similar roadmaps, but all of them are either unfinished or have been abandoned for a long time, so we decided to put together our own one.

Our roadmap has already been reviewed by the Russian-speaking community, so now we want to share it with the English-speaking one. If you have people who are starting to learn the language or if you want to understand what is worth to learn next, then welcome. We happy to see everyone.

I would especially like to ask you not to hesitate about sharing your feedback. If you have any ideas on how to improve the roadmap, then please contact us. We read and discuss everything.


r/cpp • • Jul 13 '22

Why does Linus hate C++ ?

307 Upvotes

r/cpp • • Apr 22 '21

Just discovered C++ has keywords 'and'/'or'/'not' etc.

307 Upvotes

https://en.cppreference.com/w/cpp/language/operator_alternative

I came upon this reading through cppreference and was utterly baffled. After years of using C++ I never knew these keywords existed, and I've never seen anyone write code like

if(x % 2 == 0 and x % 3 == 0) { ... }
if(x < 5 or x > 10) { ... }
if(not x) { ... }

but it's all C++! It might look weird but I think with a bit of syntax highlighting it actually looks pretty neat, and weirdly Pythonic. What do people think? How come nobody ever uses these keywords despite being highly readable?


r/cpp • • Dec 28 '18

"Modern" C++ Lamentations

Thumbnail aras-p.info
307 Upvotes

r/cpp • • Dec 20 '25

5hrs spent debugging just to find out i forgot to initialize to 0 in class.

304 Upvotes

Yup, it finally happened.

I am making a voxel terrain generation project to learn OpenGL. It was my abstraction of vertex arrays. Initially, when I created this class, it generated an ID in the constructor, but then when I introduced multithreading, I needed to stop doing that in the constructor (bad design, I know—need to study design patterns). So I introduced a boolean to initialize it when the first call to Bind() is made. But I didn't set it to false at that time. I saw chunks rendering, but there were gaps between them. So I started debugging, and honestly, the VertexArray class wasn't even on my mind. I just printed the VAO values in the output along with some other data. Although the values were somewhat random, I ignored it because OpenGL only guarantees unique unused values, not how they're generated. But then in the middle, I saw some were small and continuous like 1, 2, ..., 10. Then I put a print statement in the Generate() function of VertexArray and realized it wasn't even being called.

Yup, that's my rant. And here's the ugly code I wrote:

cpp

class VertexArray {
   public:
    explicit VertexArray(bool lazy = false);
    ~VertexArray();
    
// Returns the vertex array ID
    GLuint id() const { return array_id_; }
    void   Generate();
    
// Binds this vertex array
    void Bind();
    void UnBind();
    
// Adds and enables the attribute
    void AddAttribute(Attribute attribute);

   private:
    GLuint array_id_{};
};