PSA: Beware converting a method to pure virtual if it might ever end up called from a destructor
While digging through an ancient base class and purging it of unused cruft, I had come across a virtual method whose implementation made no sense. Curious as to why this bogus implementation wasn't causing problems, I checked all the subclasses and found they all overrode the method and none of them called the base class implementation. So I stuck a breakpoint in the base class implementation and did a bit of testing to confirm that it was never called.
Being a "smart", "senior" C++ developer, I said, "Let's throw out this pointless and confusing base class implementation and make the method a pure virtual instead! That much more clearly expresses what's going on here, and prevents anyone from accidentally calling this dumb implementation!" So I did.
Fast forward a month and I hear of devs experiencing an occasional crash on application shutdown, with the backtraces suggesting it might have something to do with the code I'd refactored. The backtraces didn't make much sense though, as they showed a jump from one method to another, despite the former never calling the latter. After exploring and ruling out several other, more significant areas of the refactor, we discovered the crash was introduced by making that base class method pure virtual!
It turns out, there existed scenarios in which that method could be called (through a couple layers of indirection) from the base class destructor. Previously, that meant calling the useless (but harmless) base class implementation, but now it meant 100% pure, uncut undefined behaviour. In this case, it appears that MSVC dealt with the UB by calling another seemingly random vtable entry instead, resulting in the crash and the surprising backtrace.
So, if you're ever working in legacy code and are tempted to make an existing method pure virtual, make extra sure that there's no possible way it could end up being called from a destructor. And if you're not 100% sure, maybe just replace the method with assert(false);
and let that simmer for a bit first.
And if you're writing new code, just don't call virtuals from your destructors. If really, really you feel must, at least put a big scary comment in place explaining how and why you are doing so. Future generations of maintenance programmers will thank you.
https://redd.it/1ehvmsq
@r_cpp
Brand new
Following a video trying to learn and I think I messed up the setup. My coding is correct with no errors but my output is giving "activating task providers cppbuild" I think it's the way I set up my files. Debug says "the program (file location) has exited with code 0 (0x00000000)." Also if anyone has a discord to help hmu
https://redd.it/1ehs1ya
@r_cpp
Hardware knowledge
Knowing about hardware helps a lot in writing efficient code in low level languages like C/C++. Although knowing more is always better than knowing less, in more high-level languages like Python hardware knowledge has less impact on writing faster code.
The topic I want to talk about in this post is branches. I cannot go into a lot of details, but I can outline the general picture and present some examples. Branches are very costly in a pipelined CPU. A branch can flush a treasure trove of already calculate data and instructions and bring the assembly line into a disastrous halt. That’s way the very clever people who design CPUs invented the branch-predictor (BP). BPs are very clever and very complex. Details of a BP is truly behind the scope of this post. But if I must summarize it in one sentence, BPs predict branches based on past data. If there is a pattern in your branch condition, the chances are the BP will find it and take advantage of it. The easiest branch to predict is a loop. The overwhelming probability is that the body of the loop will be execute as opposed to the next statement after the loop. So, the only time that you can help and optimize your code is when your branch condition is truly random or has multiple parts to it and logical sum of all conditions confuses the BP.
First thing first, always optimize by measuring against a reasonable baseline. Only a fool blindly optimizes something. As far as I know, there is no processor in the market that provides an instruction set to communicate with BP. So, you cannot tell BP what to do. Your compiler may have the knowledge of BP’s logic and rearrange the code to make the predication easier. What you can do is to eliminate the branch or make the branch simpler. Usually when you eliminate a branch or simplify it you end up doing more work (more instructions are executed). But that’s ok, because CPUs have a lot of parallel computing power to spare. It is an art form to utilize all CPU components 100%. But always, always measure.
For example, in the following snippet the second version is a lot faster:
std::vector<int> result(N);
for (size_t i =0; i < N; ++i) {
if (cond) result[i] = 10;
else result[i] = 5;
}
// VS.
std::vector<int> result(N, 5);
for (size_t i =0; i < N; ++i) {
if (cond) result[i] = 10;
}
In the following example, you can eliminate the branch, even if as I mentioned above it results in more work to be done.
sum += cond ? expr1 : expr2;
// VS.
term[2]= { expr2, expr1 };
sum += term[bool(cond)];
Logical expressions in C++ have a short-circuited evaluation. So, although something like “if (cond1 || cond2)” appears as one conditional branch to you. To hardware it is two branches. And that can (always measure) confuse the BP. So, look at the following example
if (x || y) … ; // Two branches
// VS.
if (x | y) … ; // One branch, if you can do it
Again, to illustrate how powerful BPs are, in the following example if BP is right, the first version will be faster. If BP is wrong the second version will be a rock star.
if (b) s += x;
// VS.
s += b * x;
Finally, almost never do this. It can fail spectacularly, if the functions are in-lined.
if (cond) f1(); else f2();
// VS.
funcptr fs[2] = { &f2, &f1 };
(fs[cond])();
​
https://redd.it/1ehor4v
@r_cpp
What's the purpose of SFINAE
I don't understand the purpose of it
We already have template specialisation to do something for a specific type.Then why use this typetraits header and conditions like is_integral and all?? Can you please help with a good example
https://redd.it/1ehfxrx
@r_cpp
Meet SymCalc - a Mathematical Library for C++ and Ruby
Hi everyone!
I am really passionate about maths, calculus, programming and the combination of those fields. From the time I've learnt calculus, I wanted to practice my skills and build a cool differentiation library.
And now that it's done, I would like to share it with you!
**Description**
It is called SymCalc (which stands for Symbolic Calculus), a library that's currently available for Ruby and C++ that makes working with mathematical functions a breeze. With SymCalc, you can:
* Create mathematical functions with any number of variables
* Evaluate these functions at specific variable values
* Simplify and print functions
* Differentiate functions easily.
The library makes the definition and differentiation process of functions as readable and as easy as possible!
**What are its potential use-cases?**
SymCalc is versatile and can be used wherever differentiation is needed. Here are a few examples:
* Root-Finding Algorithms: Implement methods like the Newton-Raphson or Halley’s method
* Deep Learning: Utilize gradient descent algorithms that require derivatives
* Education: An excellent tool for new-comers in math or programming to experiment with functions or dive into SymCalc’s source code.
**Key Strength**
One of SymCalc’s main strengths is that you don’t need to rewrite derivative functions every time you test something new. A simple .derivative() function call does the job!
**Check it out!**
If you are interested, you can visit SymCalc's website - [https://symcalc.site](https://symcalc.site) - for everything from an intro to examples
SymCalc is open-source, so it's also available on GitHub under symcalc/symcalc-cpp and symcalc/symcalc-ruby
I'd be happy to hear your thoughts on SymCalc, and potential ideas for improvement!
Thanks for checking out this project!
https://redd.it/1ehfd3q
@r_cpp
Why do some devs go with Qt instead of JUCE for audio projects?
Both are C++ frameworks but JUCE scores better in cost and audio feature set. I read on HN that EAW Resolution (LOUD Speaker modeling) was first written in JUCE then later ported to Qt when LGPL license became available.
https://news.ycombinator.com/item?id=6509048
https://eaw.com/wp-content/uploads/2021/09/Resolution-2-User-Guide.pdf#page=137
Plus Audacity is switching from wxWidgets to Qt which is a lot of work.
-https://forum.audacityteam.org/t/custom-button-bar/48687/2
https://x.com/Tantacrul/status/1617528302062964739
I did come across one commercial product that uses both. Qt for GUI and JUCE for audio. https://www.youtube.com/watch?v=QlirdL4JORc#t=6m0s
Here is another sample project https://github.com/torarnv/jucexqt
https://redd.it/1ehd6vq
@r_cpp
Feedback for JSON parser
https://github.com/vicetrice/CppJsonParser
https://redd.it/1eh2ytr
@r_cpp
Tutorial: REST, WebSocket and raw TCP with CAF
When we announced CAF 1.0 recently on Reddit, we've basically got the question "OK, but what is it good for?"
To showcase some of the newer features in CAF, we've put together a full, self-contained example application that implements a backend service for a warehouse: https://www.interance.io/learning/cpp/tutorial/warehouse-backend
The sources, including a CMake setup to automatically fetch and build CAF alongside the application is available at GitHub: https://github.com/interance/warehouse-backend-example
https://redd.it/1egut1l
@r_cpp
Numerical Relativity 101: Simulating spacetime on the GPU
https://20k.github.io/c++/2024/07/31/nr101.html
https://redd.it/1eguec9
@r_cpp
Tools for understanding a codebase
Hi all. I have joined a team working on a very old, large and complex C++ codebase and I am wondering if anyone knows of any tools that can help understand a codebase and perhaps how it exists in memory over time.
-
For example, a tool that shows a diagram of the classes being used and how they are nested over time would probably be useful, or something that visually shows the application flow.
-
Alternatively, I'd be interested in hearing how you guys approach this kind of thing.
https://redd.it/1egoqkm
@r_cpp
getting error in 2d vector in Mac
//when i am running this code in my vscode it showing me this error(watch below code)
#include <iostream>
#include <vector>
using namespace std;
int main(){
vector<vector<int>> vect
{{1, 2},{4, 5, 6},{7, 8, 9, 10}};
for (int i = 0; i < vect.size(); i++)
{
for (int j = 0; j < vect[i\].size(); j++)
{
cout << vect[i\][j\] << " ";
}
cout << endl;
}
return 0;
}
>>error: a space is required between consecutive right angle brackets (use '> >')
vector<vector<int>> vect
\^\~
> >
ji.cpp:10:26: error: expected ';' at end of declaration
vector<vector<int>> vect
\^
;
2 errors generated.
https://redd.it/1eglms6
@r_cpp
How to Hide Implementation Details in a Static Library?
Hi Everyone, I'm building a static library(.lib) and running into a problem where my source code metadata, like function names and debug info, is being included. I want to make sure only a few public interfaces are visible and hide all other implementation details. How can I compile my library so that it includes all the necessary code but keeps the internal details hidden? Any tips on achieving this with GCC/Clang or MSVC would be appreciated!
https://redd.it/1egikf8
@r_cpp
why can't my script get the OpenGLRenderer.hpp file
I'm struggling to get my engine.hpp file to access my OpenGLRenderer.hpp file and I have no idea why it can't find the file, the code looks like this in the former
#pragma once
#include<string>
#include "src/Render/OpenGLServer.hpp"
namespace Mordred
{
const int height = 600;//height
const int width = 800;//width
const std::string name = "Mordred Engine";// window name
void run(); //function to run the window
}#pragma once
#include<string>
#include "src/Render/OpenGLServer.hpp"
namespace Mordred
{
const int height = 600;//height
const int width = 800;//width
const std::string name = "Mordred Engine";// window name
void run(); //function to run the window
}
and this in the later
#include "flecs.h"
namespace Mordred
{
namespace OpenGLRenderer
{
ecs_world_t *world = ecs_init();
void Start(ecs_iter_t *it);
ECS_SYSTEM(world, Start, EcsOnStart, 0);
}
}#include "flecs.h"
namespace Mordred
{
namespace OpenGLRenderer
{
ecs_world_t *world = ecs_init();
void Start(ecs_iter_t *it);
ECS_SYSTEM(world, Start, EcsOnStart, 0);
}
}
any my file structure looks like this, any reason it can't get the file
[https://imgur.com/a/EyX0FrE](https://imgur.com/a/EyX0FrE)
https://redd.it/1eggj88
@r_cpp
I would like to expand on my skills.
Hello Everyone,
As the title suggests, I want to expand my skills with C++. I have tried creating multiple applications and I never finish them. I want to make something a little more advanced, I want to learn when to use pointers, I want to learn how to make stuff with API's (and make my own), I want to learn more about C++ at an expert level. I feel that the only way I can get any knowledge on C++ beyond the initial basics is by using Chat-GPT, which I feel makes me a bad programmer. How did you all get to the point of being proficient at programming with C++, what did you first make, and how do you go about actually coding? To elaborate, do you plan stuff out with UML, flowcharts, etc., or do you just go in?
https://redd.it/1eg93nd
@r_cpp
how are you using new tools for native app development?
what new technologies have improved your ability to deliver/ maintain more stable native apps? asking about things like build systems, packaging systems, containerization technologies, nix, etc etc. these are the only ones I could think of, but I haven't been able to integrate them into my native app dev workflow. please teach me your superior and productive ways!
https://redd.it/1eg888f
@r_cpp
ecs-cpp: A C++20 ecs library designed around type safety, now extended with attributes/effects support
https://github.com/annell/ecs-cpp
https://redd.it/1ehse0h
@r_cpp
I need advice.
Greetings,
So i just started learning c++ and decided to use the book c++ programming principles by Bjarne Stroustrup. I have did a little bit of Python and MATLAB previously but didn't go deep into it. I just wanna know if someone can help me better understand programming and what i should be doing apart from learning from the book and trying out all the problems within the book.
https://redd.it/1ehp17n
@r_cpp
C++ 23 constexpr interval_map
https://github.com/Farravid/farra_interval_map
https://redd.it/1ehn97q
@r_cpp
Any modern C++ libraries for discrete event simulations out there?
I can only find some pretty old libraries that even predate C++98, but it seems there is nothing for discrete event simulation for modern C++ out there. Am I missing something? I really don't want to reimplement all the event queue and the event handling from scratch!
https://redd.it/1ehh7r5
@r_cpp
How to compress out interior padding in a std::pair and why you don't want to - The Old New Thing
https://devblogs.microsoft.com/oldnewthing/20240731-00/?p=110069
https://redd.it/1eh9af5
@r_cpp
CUDA equivalent of Agner Fog Manuals
Hi all,
I seek your advice on building skills in writing CUDA code. While I was learning C++, the optimization manuals by Agner Fog have been of great help where he gives detailed intuition on several optimization tricks.
I'm just beginning to learn CUDA now. Ultimately, I would want to write optimized CUDA code for computer vision tasks like SLAM/6D pose estimation, etc.(Not deep learning).
In the context of of this, one book that usually props up is Programming Massively Parallel Processors by David and Hwu. However, it's 600+ pages and seems to go too much into depth. Are there any alternatives to this book that:
1: teaches good fundamentals maintaining balance of breadth, depth, quality and quantity
2: teaches good optimization techniques
Would also appreciate if you can recommend any books on optimizing matrix operations like bundle adjustment, etc. C++/C/CUDA.
https://redd.it/1eh2ix5
@r_cpp
C++
guys I've been learning c++ for 2 weeks, and I have a question, is using "async await" hard in c++ ? I know it depends but lets say I wanna use it to send post requests and the goal is to send them in a Asynchronous way
https://redd.it/1egve0g
@r_cpp
Once more about the rule of 5
https://www.sandordargo.com/blog/2024/07/31/rule-of-5-once-again
https://redd.it/1egqlw7
@r_cpp
Busco profesor c++
Hola buenas, soy Sergio, tengo 21 años y estoy aprendiendo actualmente c++ para crear mis propios proyectos y encontrar trabajo como programador, tengi un nivel muy básico y querría dar clases varias veces a la semana 4-5 a la semana durate unos cuantos meses. Obvimente pago por cada clase y respecto a los horarios se tendría que hablar pero tengo mucha disponibilidad.
Si ya de paso sabéis ensamblador mejor, porque me gustaría combinarlo, pero si no sabéis no pasa nada lo primero es c++.
Cualquier cosa mandarme mensaje privado
https://redd.it/1ego4hh
@r_cpp
Linked List C++ Tutorial | Template Class
https://youtube.com/watch?v=6_eSwyj4ILY&si=FZBb8ybJujXY_kAq
https://redd.it/1egjn1v
@r_cpp
ICPP - Running C++ in anywhere like a script
I'm so excited to announce that our new open source product ICPP v0.1.0 which can run C++ in anywhere like a script is out, now you can download it at the release page.
# ICPP - Running C++ in anywhere like a script
Interpreting C++, executing the source and executable like a script.
Writing powerful script using C++ just as easy as Python;
Writing hot-loading C++ script code in running process;
Based on [Unicorn Engine](https://github.com/unicorn-engine/unicorn.git) qemu virtual cpu and [Clang/LLVM](https://github.com/llvm/llvm-project.git) C++ compiler;
Integrated internally with Standard C++23 and Boost libraries;
To reuse the existing C/C++ library as an icpp module extension is extremely simple.
# Comparison
|\|Source|Executable|Package|Memory Resident|Remote|
|:-|:-|:-|:-|:-|:-|
|ICPP|C++|ARM64/X86_64 Object|imod for *.icpp|iopad/icpp-gadget|icpp-server|
|LLI|C++|LLVM-IR Bitcode|N/A|N/A|N/A|
|Python|Python|Bytecode|pip for *.wheel|N/A|N/A|
|Frida|JavaScript|Bytecode|N/A|frida/frida-gadget|frida-server|
https://redd.it/1egh6lc
@r_cpp
Resources to Prepare for IOI
Hey. I want to prepare for ZCO&INOI (Indian selection round for IOI). It is in both December and April. From where should I learn CP? The syllabus is https://www.iarcs.org.in/inoi/online-study-material/topics/, ZCO only covers the basic topics. But for INOI, The syllabus is the same as of IOI.
https://redd.it/1egdl3w
@r_cpp
Space Game coded by C++/SDL2
My small project in Advanced Programming course when I was freshmen.
https://github.com/deconasser/Space-Game-Cplusplus-SDL2
If you're interesting and my proj helps you a lot. Pls give me 1 star for my dedication.
https://redd.it/1eg9sws
@r_cpp
Reading .desktop files
I use void linux and I'm currently writing a c++ program that is meant to monitor my computer activity to give me a visual representation of how im spending my time on my computer. Currently im stuck at a point where im trying to get the category of a program from its .desktop file so that they can be organized by category when i map the data to a pie chart. Im doing std::ifstream deskFile(filepath) and when i check to see if the file is open it always says its failed to open the file as there is supposedly "no such file or directory". I know this is not true since i have a txt file with all the errors and file paths and all of the paths lead to actua files. What would be causing this do you think? Im pretty sure its not permissions because my executable has -rwxr-xr-x and the .desktop files are -rw-r--r--. Ay help that could be provided woud be amazing, thank you!
https://redd.it/1eg7v16
@r_cpp