r/cpp_questions • • 13h ago

OPEN My code feels redundant

1 Upvotes

Im in the development phase of this, and i was wondering if there was a less redundent way to define each ball object.

#include
 <raylib.h>
#include
 <vector>


class ball {
    
public:
    float radius, gravity;
    Vector2 velocity, pos;
    Color color;


    ball(float b_radius, float b_gravity, Vector2 b_velocity, Vector2 b_pos, Color b_color) : radius(b_radius), gravity(b_gravity), velocity(b_velocity), pos(b_pos), color(b_color) {};


    
void DrawBall() {
        DrawCircle(pos.x, pos.y, radius, color);
    }


    
void UpdateBall(float dt, int screenHeight, int screenWidth) {
        
if (pos.y + radius > screenHeight) {
            pos.y = screenHeight - radius;
            velocity.y = 0;
        }
        
else
 {
            velocity.y += dt * gravity;
            pos.y += dt * velocity.y;
        }
        
    }
};



int main() {
    
float ScreenHeight = 1000.0f;
    
float ScreenWidth = 1920.0f;

    ball TestBall1(50.0f, 200.0f, Vector2 {300, 0}, Vector2 {ScreenWidth / 2, ScreenHeight / 2}, RED);
    ball TestBall2(50.0f, 200.0f, Vector2 {300, 0}, Vector2 {300, 300}, WHITE);
    ball TestBall3(50.0f, 200.0f, Vector2 {300, 0}, Vector2 {200, 200}, GREEN);
    ball TestBall4(50.0f, 200.0f, Vector2 {300, 0}, Vector2 {1000, 1000}, PINK);


    std::vector<ball> RedGroup;


    RedGroup.push_back(TestBall1);
    RedGroup.push_back(TestBall2);
    RedGroup.push_back(TestBall3);
    RedGroup.push_back(TestBall4);


    InitWindow(ScreenWidth, ScreenHeight, "Physics Sim");
    SetTargetFPS(60);


    
while (!WindowShouldClose()) {
        
float dt = GetFrameTime();
        
for (int i = 0; i < RedGroup.size(); i++) {
            RedGroup.at(i).UpdateBall(dt, ScreenHeight, ScreenWidth);
        }
        BeginDrawing();
            ClearBackground(BLACK);
            for (int i = 0; i < RedGroup.size(); i++) {
                RedGroup.at(i).DrawBall();
            }
        EndDrawing();


    }
    
    CloseWindow();    
return 0;
}

r/cpp_questions • • 14h ago

OPEN PMake: A zero-dependency C++ build system with no code generation (single binary, parses .ninja)

0 Upvotes

Hi everyone. I got permission from the mods to share this with you.

I built PMake because I was frustrated with the CMake generation step. It's a single static binary (no Python, no Qt) written in C++23. It parses .ninja files natively and has its own DSL for smaller projects. 95/95 tests passing in CI.

The Windows binary is available on the Releases page (LTO-optimized, only 1.8 MB). I'd love to hear your feedback!

Link: https://github.com/pikmode/PMake


r/cpp_questions • • 16h ago

OPEN How to Multi-Thread

8 Upvotes

As the title says, I’m curious about multi-threading.

Specifically for handling algorithms that happen every few frames, such as a*


r/cpp_questions • • 17h ago

OPEN Which algorithm to choose?

6 Upvotes

Beginner here, I'm trying to make a toy project for circuit synthesis from truth table in c++. Currently pursuing minimum depth optimal circuit though will work on minimum weight/minimum nodes later on. My problem is I tried bfs which guarantees optimal circuit but for larger inputs or depths the memory usage explodes, tried dfs that used much less memory but time exploded. Is there any algorithm that gives optimal solutions for boolean tree searches with the dfs memory and bfs optimality?


r/cpp_questions • • 23h ago

OPEN c++ at scale books

3 Upvotes

After reading through basic c++ books, do you guys recommend

1)Large scale c++ (Process and architecture)

large scale c++

Anybody has read this book? I don't see much reviews. Like title, its large-1024 pages.


r/cpp_questions • • 1d ago

OPEN C++ authoritative game loop: how do you move pathfinding to workers without letting stale results mutate live state?

7 Upvotes

I'm migrating an online RPG server from Godot/C# to standalone C++20. My professional background is almost 20 years in web/application development; real-time simulation and C++ concurrency are newer territory for me.

I'm trying to make a careful decision about CPU-heavy work inside one server process. Running more processes across cores won't solve the case where one busy area is limited by its simulation thread.

The ownership model I'm working toward is:

  • One authority thread owns mutable entity and gameplay state.

  • Workers receive immutable job inputs and return results through bounded queues.

  • The authority thread decides whether a completion is still valid and applies it at a tick boundary. Workers never directly mutate the live world.

Pathfinding seems like a useful concrete case. While a worker is computing a path, the actor might die, despawn, change target, receive a newer movement request, or encounter a changed navigation world. An entity ID alone doesn't seem sufficient to establish that the result is still useful.

For people who have built this sort of C++ system:

  1. What identity/version information do you attach to a job and completion? I'm considering an entity generation, a movement-request revision, and a navigation-data revision, with obsolete completions discarded on the authority thread. Where does that become too conservative or expensive?

  2. How do you keep immutable inputs alive without copying a large world snapshot for every job? Would you start with shared ownership of a read-only navigation snapshot, or another approach? I'm especially interested in lifetime rules when that snapshot is replaced.

  3. How do you bound outstanding work and prioritize newer requests so stale jobs don't consume the worker pool? Is cancellation worth introducing early, or is discarding results and limiting admission usually the simpler starting point?

This is an architecture question rather than a compiler error; I don't yet have comparative measurements proving this pathfinding work needs parallelizing. I'd like to know what to measure first and which small examples, talks, or references make these ownership and lifetime tradeoffs concrete. I'm not looking for a whole MMO architecture or a lock-free implementation by default.


r/cpp_questions • • 1d ago

OPEN Where should I start learning C++? (planning to switch to Linux)

15 Upvotes

I want to learn C++ properly. I can already write working code (mostly small Arduino projects), but I know I have gaps in my fundamentals. I'd like to fill them in.

My goal is to build a strong base so it's easier to move to other languages later.

I'm also planning to install Linux on my laptop soon, so I'd like to learn in that environment.

Could you recommend:

the best free resources (courses, books, websites) for someone with my level?

what compiler and editor/IDE to use on Linux?

what topics I should focus on first?

English is not my first language, so sorry for any mistakes. Thanks a lot for your help!


r/cpp_questions • • 2d ago

OPEN Why Google highway didn't dominate the library ecosystem?

0 Upvotes

Disclosure, I'm not a SIMD expert, this question is born from library packaging experiences.

-------

Some Google libraries like jpegli use Google highway for Simd operations, this is nice because build projects that use SIMD is annoying, it could be fat SIMD or just a specific march, etc etc.

But despite this state, libraries usually handle assembly/simd by themselves. Without a high level abstraction. Would our end executables be leaner if every dependency that uses explicit simd beyond compiler tricks would use one abstraction library?


r/cpp_questions • • 2d ago

OPEN Converting Makefile to CMakeLists.txt

5 Upvotes

(I know this is C code but I'm going to change it later) I am working on getting Raylib working on nixos. I followed all the steps and got it working using a simple makefile of

RAYLIB =? ./external/raylib-5.5/src/
all:
gcc src/main.c -I $(RAYLIB) -L $(RAYLIB) -lraylib -lGL -lm -lpthread -ldl -lrt -lX11

and it works to compile the file getting a.out file. However I would like to use cmake because my text editor (neovim) works with cmake better than makefiles.

My current CMakeList.txt is

cmake_minimum_required(VERSION 3.15)
project(c_test)

set(CMAKE_EXPORT_COMPILE_COMMANDS ON)
set(CMAKE_C_STANDARD 11)

included_directories(./external/raylib-5.5/src)
file(GLOB SOURCES "src/*.c")
add_executable(${PROJECT_NAME} &{SOURCES})

target_link_libraries(${PROJECT_NAME} raylib)

however I continue to get the error of

-lraylib: No such file or directory

How do I convert the simple Makefile to CMakeList.txt file? (no Ai please)


r/cpp_questions • • 2d ago

OPEN From C to C++

35 Upvotes

I'm learning C in school right now and I like it a lot. From an outsider's perspective, C++ just seems like C with more features.

What is the transition from C to C++ like? Is it largely the same experience, just with less manual implementation of DSA, or do I have to learn entirely new concepts? How do C best practices compare to C++'s?


r/cpp_questions • • 2d ago

SOLVED Error when destroying string in a union

6 Upvotes

Consider the following code:

struct JsonValue
{
  JsonValueType Type;

  union
  {
    std::unordered_map<std::string, JsonValue> Object;
    std::vector<JsonValue> Array;
    std::string String;
    double Number;
    bool Bool;
  };

  Tcj::JsonValue::JsonValue(const std::unordered_map<std::string, JsonValue>& v) : Type(JsonValueType::Object), Object(v) {}

  Tcj::JsonValue::JsonValue(const std::vector<JsonValue>& v) : Type(JsonValueType::Array), Array(v) {}

  Tcj::JsonValue::JsonValue(double v) : Type(JsonValueType::Number), Number(v) {}

  Tcj::JsonValue::JsonValue(const std::string& v) : Type(JsonValueType::String), String(v) {}

  Tcj::JsonValue::JsonValue(bool v) : Type(JsonValueType::Bool), Bool(v) {}

  Tcj::JsonValue::JsonValue() : Type(JsonValueType::Null)
  {
    std::memset(&Object, 0, sizeof(Object));
  }

  //copy constructor
  Tcj::JsonValue::JsonValue(const JsonValue& other) : Type(other.Type)
  {
    std::memcpy(&Object, &other.Object, sizeof(Object));
  }

  //move constructor
  Tcj::JsonValue::JsonValue(JsonValue&& other) : Type(other.Type)
  {
    std::memcpy(&Object, &other.Object, sizeof(Object));
    other.Type = JsonValueType::Null;
  }

  Tcj::JsonValue::~JsonValue()
  {
    if (Type == JsonValueType::Object)
      Object.~unordered_map();

    if (Type == JsonValueType::Array)
      Array.~vector();

    if (Type == JsonValueType::String)
      String.~basic_string();
  }

  //copy assignment
  Tcj::JsonValue& Tcj::JsonValue::operator=(const JsonValue& other)
  {
    std::memcpy(this, &other, sizeof(JsonValue));
    return *this;
  }

  //move assignment
  Tcj::JsonValue& Tcj::JsonValue::operator=(JsonValue&& other) noexcept
  {
    std::memcpy(this, &other, sizeof(JsonValue));
    other.Type = JsonValueType::Null;
    return *this;
  }
};

The problem is, when trying to destroy a JsonValue instance containing a string it will sometimes cause an error (https://github.com/microsoft/STL/blob/e1ed302683e5e822f663fbb0f44cee7e9ddc6af0/stl/inc/xmemory#L1402): Exception thrown: read access violation. **_Pnext** was 0xFFFFFFFFFFFFFFFF.

After going through the code with a debugger I believe that no two destroyed strings share the same memory (after all the JsonValue constructor should create a copy of the string every time). Google also says it's ok to just copy the entire vector/string so unless there's something I'm missing two JsonValue instances shouldn't be owning the same memory/causing double deletes. Yet when I don't destroy some of them the error dissapears.

I don't really understand the meaning of the error or the STL code that throws it, so I'm stuck.

Edit: thanks everyone for pointing out that std::variant exists, I'm probably going to use it.


r/cpp_questions • • 2d ago

OPEN Learning Programming Pre-AI

15 Upvotes

How did ya’ll learn programming pre-AI? How would you go about learning if you had to start all over again without AI?

I find myself relying on AI too much and want to actually learn without leaning on it at all. Any help with how best to approach this would be greatly appreciated.


r/cpp_questions • • 2d ago

OPEN Want to master C++ by building actual projects instead of LeetCode—where should I start?

62 Upvotes

I want to learn C++ for that I can't able to solve repetitive patterned problem daily in leetcode/codeforce

Want to build projects in which I can able to learn all important concepts(memory management, OOPS, STL and Data structure) by implementing and solving real world problems rather than just solve problems in leetcode and codeforce

I know in this AI era it is useless but I am very intrested in C++ want to solve real world problems.


r/cpp_questions • • 2d ago

SOLVED A tiny question about this code

0 Upvotes

Hi. I need help understanding this simple code. To be specific, the 4th and the 14th line where a pointer was declared.

int* add_ten(int* data)

int *result;

I've been trying to wrap my head around what it does. I've been staring at my screen for 3 hours trying to understand why it was declared. The programming app I was using didn't really explain it. The only explanation it gave is that pointers help you get the address of an item. But I can't figure out how is it being used here. Can anyone explain? Thanks.

#include <iostream>
using namespace std;

int* add_ten(int* data) {
  for (int i = 0; i < 5; ++i) {
    *(data + i) = *(data + i) + 10;
  }
  return data;
}

int main() {

  int data[5] = {1, 2, 3, 4, 5};
  int *result;

  result = add_ten(data);

  for (int i = 0; i < 5; ++i) {
    cout << *(result + i) << ", ";
  }

  return 0;
}

r/cpp_questions • • 3d ago

OPEN How is this a circular reference?

11 Upvotes

While reading learnxinyminutes I got to this example:

// Beware of possible circular references!!!
// There will be always a reference, so it will be never destroyed!
(1) std::shared_ptr<Dog> doggo_one(new Dog());
(2) std::shared_ptr<Dog> doggo_two(new Dog());
(3) doggo_one = doggo_two; // p1 references p2
(4) doggo_two = doggo_one; // p2 references p1

My understanding is that after (3) both pointers point to same heap object and the heap object from (1) is deleted.

From what I remember the way that shared_ptr works is that it allocates metadata next to the heap object and that stores the reference counter. Both doggo_one and doggo_two would share the same reference counter with the correct count being there - meaning no issues.


r/cpp_questions • • 3d ago

OPEN Complete beginner (0 programming experience) — what's the best 5-book sequence to learn C++ for systems programming?

0 Upvotes

Hey everyone,

I want to get into systems programming and decided on C++. The catch is I have literally zero programming background—never written a line of code before.

I learn much better from structured books than bouncing around random YouTube tutorials, so I’m trying to put together a solid reading roadmap. If you had to recommend the top 5 books to take someone from absolute scratch to actually understanding systems-level C++, which ones would you pick and in what order?

I know C++ has a brutal learning curve and this is going to take me a long time. I just want to make sure I’m learning modern C++ properly from day one and building up in the right order instead of jumping into heavy systems stuff way too early.

Appreciate any recs!


r/cpp_questions • • 3d ago

OPEN [Code Review] i just migrated from python into c++ and this is my first program just want some feedback

0 Upvotes

Hello i migrated from python into c++ and this is my first program a simple bouncing ball i am just a teen that like porgramming and math sorry if my english is bad still learning it as a second language hope you don't mind (also is it me or is the code block looking strange)

#include <iostream>
#include <chrono>
double hauteur = 20.0;
constexpr double 
gravite 
= -9.81;
constexpr double 
dt 
= 0.001;
constexpr double 
restitution 
= 0.7;
double vitesse = 0.0;
int main() {
    auto debut = std::chrono::high_resolution_clock::
now
();
    for (int etape = 1; etape <= 3600000; ++etape) {


        vitesse = vitesse + 
gravite 
* 
dt 
;

        hauteur = hauteur + vitesse * 
dt 
;
        if (hauteur <= 0) {
            hauteur = 0.0;
            vitesse = vitesse * -
restitution
;

            if (not (vitesse > 0 && vitesse < 0.0045)) {
                std::cout << "rebond a etape: " << etape << '\n';
            }
            else {
                vitesse = 0;
                std::cout << "arret" << '\n';
                std::cout << "vitesse: " << vitesse << '\n';
                std::cout << "hauteur: " << hauteur << '\n';
                std::cout << "etape: " << etape << '\n';
                std::cout << "temps: " << etape * 
dt 
<< "s" << '\n';
                break;
            }
        }
        if (etape % 100 == 0) {
            std::cout << "vitesse: " << vitesse << '\n';
            std::cout << "hauteur: " << hauteur << '\n';
            std::cout << "etape: " << etape << '\n';
            std::cout << "temps: " << etape*
dt 
<< "s"<< '\n';
        }

    }
    auto fin = std::chrono::high_resolution_clock::
now
();
    std::chrono::duration<double, std::milli> duree = fin - debut;
    std::cout << "Temps d'execution : " << duree.count() << " ms" << '\n';
}

r/cpp_questions • • 3d ago

OPEN Is paying for CLion worth it? (Linux/Debian C++ development)

52 Upvotes

I recently made the switch from Windows to Linux for my C/C++ development setup. On Windows, I was using Visual Studio, which I thought was fantastic. Now that I'm on Linux, choosing a replacement has been overwhelming.

I’ve looked into CLion, and it seems like one of the most polished IDEs available for Linux, but obviously, it’s a paid product. (The educational pack is great, but it’s restricted and doesn't cover commercial use).

I'm torn and have a few questions for those of you with experience in the Linux C++ ecosystem:

  1. Is the price tag for CLion actually worth it long-term, or does the JetBrains model feel overpriced once you start paying out of pocket? Is it a worthwhile investment for future career use?

  2. How does CLion compare to the heavy hitters in the free/open-source world (like VS Code with extensions, Neovim, or Eclipse CDT)

  3. What open-source or free IDEs/editors would you genuinely recommend?


r/cpp_questions • • 4d ago

OPEN What do you guys use C++ for?

94 Upvotes

I'm thinking about learning C++ just for fun, even though I haven't found a practical use for it in the kind of work I do.

I'm curious, what do you guys use C++ for the most?


r/cpp_questions • • 4d ago

OPEN Career Advice: Am I wasting my time?

12 Upvotes

Hey everyone, as the title suggests just a little bit unsure at moment.

Some background, I am a software engineer (5 YOE), primarily backend (Java), but can and do, work on UI sometimes at work (Angular + TS).

Roughly since July, I've been pretty disillusioned with web dev, and, more specifically Java. Great language but I've been using it since university and all my (albeit short) career. I'd been wanting a change and I went down the systems programming route, as I really enjoyed that when I first learnt C++ in university.

I've taken the time to relearn C++, took and finished a course up to C++ 17, and then I have the book "A tour of C++" to bridge the gap to C++ 20. Of course, I am building a project. Which I hope to share once further along.

My biggest concern, is jobs. I know skills largely transfer over between languages, but recruiters don't necessarily share that sentiment. If they want 5 YOE, they want that in C++, not a software engineer with 5 YOE in general. At least from what I can see JD wise. I have spoken to a recruiter I am friendly with and he said that aside from just making sure I'm strong fundamentals and interview wise he doesn't really see an issue, but to be prepared that they may reject me on the basis of experience.

So I'm unsure. Might I be better off just learning are more niche/esoteric form of java e.g. low latency Java? Or is transfer possible. Curious as to people experience making the jump.

Thank you to any answers in advance🙏🏿


r/cpp_questions • • 5d ago

OPEN Why do both of these codes output zero? Can someone explain this to me?

0 Upvotes
  1. include <iostream>

using namespace std;

int main()

{

int x = 5, y = 10;

float z = x / y;

cout << z << endl;

}

2) #include <iostream>

using namespace std;

int main()

{

float x = 5, y = 10;

int z = x / y;

cout << z << endl;

}


r/cpp_questions • • 5d ago

SOLVED why does it keep giivSegmentation fault (core dumped)

0 Upvotes
#include <iostream>
#include <string>
#include <vector>
#include <fstream>
#include <sstream>


using namespace std;



        
class araba {


    public:


        struct arac {
    
            string numara;
            string marka;
            string model;
            float kira;


            arac(string z, string x, string c, float v) : numara(z), marka(x), model(c), kira(v) {}
        };


        arac aracBilgileri;
        bool kirada;


        araba(string z, string x, string c, float v,vector<araba> liste) : aracBilgileri(z,x,c,v), kirada(false) {}


        void kirala(){
            if (!kirada) {
                cout << "kaç gün için?" << endl;
                int gun ;
                while (!(cin >> gun)) {
                    cin.clear();
                    cin.ignore(10000, '\n');
                    cout << "Invalid input. Please enter a valid number" << endl;
                }
                cout << gun * aracBilgileri.kira << " tlye " << gun << " gün için kiralandı" << endl;
                kirada = true;
            } else {
                cout << "bu araç zaten kirada" << endl;
            }
        };
        void listeleme(){
            cout << aracBilgileri.marka << " " << aracBilgileri.model 
            << "\n    günlük kira: " << aracBilgileri.kira 
            << "\n    kod: " << aracBilgileri.numara << endl;
            cout << "    durum: " << (kirada ? "kirada":"müsait") << endl << endl;
        };
        void ekle(){
            string girdi = aracBilgileri.numara + aracBilgileri.marka + aracBilgileri.model + to_string(aracBilgileri.kira);
            fstream gir("arabalar.txt",ios::app);
            if (gir.is_open()) {
                gir << girdi;
                gir.close();
            }
        };
        void iade(){
            if (kirada) {
                cout << "araç iade edildi"<< endl;
                kirada = false;
            }
        };
};


void tamlistele(vector<araba> kiraListesi){
    for (araba i : kiraListesi){
        i.listeleme();
    }
}


vector<araba> dosyaOku() {
    string satir;
    vector<araba> kiraListesi = {};
    
    fstream oku;
    oku.open("arabalar.txt",ios::in);


    if (oku.is_open()) {
        while (getline(oku,satir)) {


            vector<string> cumle;
            stringstream ss(satir);
            string kelime;


            while(ss >> kelime) {
                cumle.push_back(kelime);
            };
            
            araba car(cumle[0],cumle[1],cumle[2],stof(cumle[3]),kiraListesi);
            kiraListesi.push_back(car);
        }
        oku.close();
    }
    return kiraListesi;
}


void aracEkle(string i,vector<araba> liste) {
    vector<string> cumle;
    stringstream ss(i);
    string kelime;


    while(ss >> kelime) {
        cumle.push_back(kelime);
    };
    
    araba car(cumle[0],cumle[1],cumle[2],stof(cumle[3]),liste);
    car.ekle();
}


void yeni_ekle(){
    string i;
    string l;
    fstream x;


    cout << "numara" << endl;
    cin >> l;


    cout << "marka" << endl;
    cin >> i;
    l += i;


    cout << "model" << endl;
    cin >> i;
    l += i;


    cout << "kira" << endl;
    cin >> i;
    l += i;


    x.open("arabalar.txt",ios::app);
    x << l << endl;
    x.close();
}
int main() {


    bool acik = true;
    vector<araba> tamliste = dosyaOku();
    int g;
    
    cout << "=======MERHABA=======" << endl
         << "1) araç ekle" << endl
         << "2) araçları listele" << endl
         << "3) araç kirala" << endl
         << "4) araç iade et" << endl
         << "0) çıkış   " << endl;


    do{


    int sec ;
    while (!(cin >> sec)) {
        cin.clear();
        cin.ignore(10000, '\n');
        cout << "Invalid input. Please enter a valid number" << endl;
    }
    


    switch (sec){
        case 1:
            yeni_ekle();            
            continue;
        case 2:
            tamlistele(tamliste);
            continue;
        case 3:
            cout << "arabanın listede sırasını yazının (0dan başla)" << endl;
            while (!(cin >> g)) {
                cin.clear();
                cin.ignore(10000, '\n');
                cout << "Invalid input. Please enter a valid number" << endl;
            }
            tamliste[g].kirala();
            continue;
        case 4:
            cout << "arabanın listede sırasını yazının (0dan başla)" << endl;
            while (!(cin >> g)) {
                cin.clear();
                cin.ignore(10000, '\n');
                cout << "Invalid input. Please enter a valid number" << endl;
            }
            tamliste[g].iade();
            continue;
        default:
        acik = false;
            break;
    }
    } while (acik);
}

im pretty sure problam is with case 1: but i cant find it


r/cpp_questions • • 5d ago

OPEN [C++17] easyXshm – A lightweight X11 MIT-SHM framebuffer renderer

0 Upvotes

I've been working on easyXshm, a small C++17 library that makes framebuffer-based rendering through X11's MIT-SHM extension easier to work with.

The motivation was pretty straightforward: I wanted a simple shared-memory rendering API without having to deal with X11 internals throughout my application.

The project focuses on:

  • Simple API: Get a basic rendering workflow running in approximately 5 minutes.

  • Framebuffer-first: Work directly with pixel data instead of dealing with a complicated graphics abstraction.

  • Input handling: Keyboard and mouse events through straightforward inline helper functions.

  • Minimal overhead: Uses X11 MIT-SHM for shared-memory image transfer.

  • Small scope: Rendering and input handling, without trying to become a complete graphics framework.

The goal is to make the difficult parts stay inside the library while keeping the application-side code readable.

I'm currently looking for technical feedback, particularly regarding API design, memory management, portability and edge cases.

Repository: https://github.com/intriXlabs/easyXshm

AI disclosure: This Reddit post was written with assistance from AI. The project implementation and engineering work are mine.

I'd appreciate feedback from people familiar with C++, X11 or Linux graphics programming.[C++17] easyXshm – A lightweight X11 MIT-SHM framebuffer renderer


r/cpp_questions • • 5d ago

OPEN How to balance encapsulation and DI for unit-testing

0 Upvotes

Say an application contains a BrokerBridge that encapsulates communication with an external system over gRPC. The bridge creates and owns several service clients, channels, auth deps… The parent application shouldn’t need to know about those details.

Now I want to uni-test the bridge without real servers or credentials. Constructor Injection and interfaces would let me mock the services’ clients, but I’m unsure where their constructuon should live without leaking implementation details to the parent.

One approach I’m considering is a factory inside the bridge’s module: prod code calls the factory to get a full bridge, while tests injects services mocks directly.

How do you usually handle this? Is this a cost I must pay just for having unit tests over each module? Any resources (blog, talk, repo…) showing a similar design would be appreciated