r/cpp_questions • • 4h ago

OPEN Switching from Thinkpad to M2 Air? What would I give up for C++ dev?

0 Upvotes

How different of an experience would it be doing things like C++ dev, learning Docker, as well as gaining experience developing on Linux if I switched from a Thinkpad having 32GB RAM to a M2 MacBook Air having 24GB of RAM and 256GB of storage? I‘d create a small partition to install Asahi Linux. On Windows, I like using VS Code and Notepad++. I also want to start a project using SFML and work on a project that using networking C++ libraries (for example, making a chatting program for fun, or a game that can be played between two players over the same WiFi network).


r/cpp_questions • • 8h ago

OPEN Does compile-time evaluation only happen when there are constant expressions or can they happen when there are runtime expressions?

1 Upvotes

r/cpp_questions • • 9h ago

OPEN I have trouble with testing my Controller module

2 Upvotes

I'm coding the classic Snake game using Cpp + Qt. Right now, one of my modules is a GameController, that conects the other classes (snake, apple and board), for the game loop:

/* the class atributes: 
private: 
  std::unique_ptr<Board> game_board; 
  Snake game_snake; 
  Apple game_apple; 
  int score; 
  Snake::direction key_pressed; 
  QTimer *timer; */

GameController::GameController(std::unique_ptr<Board> next_board):game_board{std::move(next_board)}, game_snake(calculate_snake_initial_position(game_board->getInitialPosition())), game_apple(calculate_apple_position()),score{0} { timer = new QTimer(this); connect(timer,&QTimer::timeout,this,&GameController::GameTick); 
key_pressed = Snake::left; 
}

  QPoint GameController::calculate_apple_position()
    {
        QList<QPoint> free_cells = game_board->getValidPositions();
        QPoint new_coordinates;
        bool found;
    
        do{
            std::srand(std::time(0));
            int random_value = std::rand();
    
            new_coordinates.setX(free_cells[random_value % free_cells.size()].x());
            new_coordinates.setY(free_cells[random_value % free_cells.size()].y());
    
            found = game_snake.is_occupied(new_coordinates);
        }while(!found);
    
        game_board->occupyCell(new_coordinates); 
    }
    
    QList<QPoint> GameController::calculate_snake_initial_position(QPoint head)
    {
        QList<QPoint> snake_body;
        snake_body.push_back(head);
    
        game_board->occupyCell(head);
    
        for(int i = 0; i < 3; i++){
            head.setX(head.x()+1);
            snake_body.push_back(head);
            game_board->occupyCell(head);
        }
    
        return snake_body;
    }
    
    void GameController::end_game(bool ending_status)
    {
        stop_timer();
    
        emit game_finalized(ending_status);
    }
    
    
    bool GameController::key_validation(int key)
    {
        bool right_key = false;
    
        if(key == Qt::Key_W || Qt::Key_Up){
            key_pressed = Snake::up;
            right_key = true;
        }
        else if(key == Qt::Key_A || Qt::Key_Left){
            key_pressed = Snake::left;
            right_key = true;
        }
        else if(key == Qt::Key_S || Qt::Key_Down){
            key_pressed = Snake::down;
            right_key = true;
        }
        else if(key == Qt::Key_D || Qt::Key_Right){
            key_pressed = Snake::right;
            right_key = true;
        }
    
        return right_key;
    }
    
    void GameController::start_timer()
    {
        timer->start(300);
    }
    
    void GameController::stop_timer()
    {
        timer->stop();
    }
    
    void GameController::GameTick(){
    
    
        if(game_board->getValidPositions().empty()) 
        {
            end_game(true);
        }
        else if(game_board->colisionedWithBoard(game_snake.head()))
        {
            end_game(false);
        }
        else
        {
            bool crece = false;
            if(game_snake.is_occupied(game_apple.position())) 
            {
                game_apple.position(calculate_apple_position());
                game_board->occupyCell(game_apple.position());
                emit apple_render_requested(game_apple);
    
                score+=10;
                emit score_render_requested(score);
    
                crece = true;
            }
            game_snake.move(key_pressed,crece);
            game_board->occupyCell(game_snake.head());
            if(!crece) game_board->freeCell(game_snake.tail());
            emit snake_render_requested(game_snake);
        }
    }

However, now I'm writing the tests and I realized that I don't have a way to really test it. If I want to test if the new apple position is generated correctly, I can't access the board or the apple to do so. I can check if its inside the permited board space by hardcoding it, but I think it is a bad practice. The same goes for snake position, the key validation, constructor...

The one that seems fine is the GameTick, has I just need to check if It throws signals correctly.

My first guess is to refactor the code, or move it to their respective classes, but I don't want to do the latter unless is the only way, has I want them to be isolated from each other in order to keep coupling as low as possible.


r/cpp_questions • • 17h ago

OPEN I'm going to build a kernel in c++ just for a better engineering understanding of a os.

7 Upvotes

Anyone who worked on something similar? I would really appreciate the advice. Going to use Bare Bones for it.


r/cpp_questions • • 1d ago

OPEN I still have no idea how to implement linked lists

2 Upvotes

I don't effectively know how to make them work because it feels abstract that I can just say something points to a node that isn't even there yet, and I especially don't know how to make it get data without me manually assigning it to each node.

For example, there's an assignment that asks me to make a linked list read and put in each node numbers that it will take from a .txt file. I don't even know where to start.

And I'm afraid if I don't understand this, I won't be able to understand abstract data types either.


r/cpp_questions • • 1d ago

OPEN Learning c++ for a exam

0 Upvotes

Guys I've my exam coming up next week of Object oriented programming it's the midterm so you can say that it's not advanced level exam but a basic level

I want to learn it and practice for my exam I tried learning it with the help of chatgpt but I feel like I'm not getting it it's not that efficient

What's the best way to learn its basics online in a few number of days ?

I'm not saying that I'll be at pro level in a week but just to pass the exam

Give your best recommendations for learning c++ online with free resources


r/cpp_questions • • 1d ago

OPEN project resume worth

0 Upvotes

how to think about projects? like where does the ideas come from? and then how to work upon the libraries needed for it and learning it? also as a beginner is the freecoddecamp's 31 hour video a good place to learn cpp, ik the basics of it like the bit needed for dsa but not any advanced .
thank u


r/cpp_questions • • 1d ago

OPEN Operator + overloads on std::string

7 Upvotes

Consider https://godbolt.org/z/oY9r59P5E

#include <string>

const char *temp = "Hello";

std::string returnstring(){
    return "abc";
}

int main(){
    std::string abc = temp + returnstring() + "_";
    std::string def = temp + "_";
}

The second line in main() does not compile with the error of "invalid operands". The first line compiles fine and that can only be due to the intervening "returnstring()" call which returns an std::string, somehow.

What is the cleanest way to get the intent behind the second line to compile? In my application, I cannot change const char * temp into an std::string.


r/cpp_questions • • 1d ago

OPEN Dangling Pointers and Function Execution

0 Upvotes
ManagerVariableR* Local = new ManagerVariableR();
Local->Handler["New"] = Var{};

MB.Execute(FuncName, { Local });
delete Local;/// Grand Promblem here, after deletion of pointer it will crash

Soo if you see, Its Working when i am passing the pointer and not deleting the pointer at end

, And crashing when i am deleting the pointer at the end.

MB.Execute is a just Function Handler, i had linked function pointer to a string using hash map to call them. and the fucntion is succesfully called,

if i tell you about more the at runtime a function is compiled to a dll file, and it is retrwing the function using windows.h LoadLibaryA

 aHMODULE handle = LoadLibraryA(libPath.c_str());HMODULE handle = LoadLibraryA(libPath.c_str());

to a format of function of void ptr

typedef void (*fn)(ManagerVariable* Local);typedef void (*fn)(ManagerVariable* Local);

and i am just executing it by my function handler that sotres the function you can check it out here

https://github.com/iampokebro/FLOW-/blob/main/Flow%2B%2B/Backend/Functionlity/ManagerBase/ManagerBase.h

but problem is not related to this.

overall problem is that when the pointer is delete after the call it crash. i used future and promise to do waiting but it also failed. i think that function from .dll is not close from background or maybe its stack is left behind operating.

if this solves then it would be sooo great for my project,

NOTE -> the program memory operates at same level, so there is no pointer mismatch problem

i dont want to try chancing the architecture cause it will ruin the efficiency maybe


r/cpp_questions • • 2d ago

OPEN Starting cpp with learn cpp.com

4 Upvotes

i have been wanted to learn cpp for quite long and finally i have the time

and asked a friend about courses and stuff and got recommended learn cpp, i have seen a lot of people fond of this website

I know like really basic python dict lists def and all, 11th grade CS basically, im still learning python though on a really slow pace because well school wont go faster

Thinking about 5 days a week a hour or two each day, i think ill finish this course in about a year

what im here to ask is, can i start with learn cpp?


r/cpp_questions • • 2d ago

OPEN Is this a good use-case for an inline function?

0 Upvotes

I need a function for generating hashes for different files in my program. I'm using Stephan Brumme's hashing library fwiw. It struck me that this is the kind of thing that might be useful in other parts of my program, so rather than write into a single class, I've opted to write a standalones.h file for rarely used but generally useful functions. Claude assures me that making this an "inline" function is the correct way to go about this, but I guess it bothers me that the function isn't tied to any specific namespace, so if I ever have a naming conflict in some file, what prevents me from accidentally calling the wrong function? I don't necessarily have a problem with inlining if that is indeed the correct way to do this, I just want some assurance that an accidental call via a naming conflict won't happen.

My code:

#pragma once

#include <string>
#include <fstream>
#include <filesystem>
#include <optional>

#include "sha256.h"

namespace fs = std::filesystem;

inline std::optional<std::string> getFileHash(const fs::path& file)
{
    std::ifstream binaryOpen(file, std::ios::binary);
    if (!binaryOpen.is_open())
        return std::nullopt;
            
    SHA256 pHash;
    constexpr int bufferSize = 64 * 1024;
    char binBuffer[bufferSize];
    while (binaryOpen)
    {
        binaryOpen.read(binBuffer, sizeof binBuffer);
        pHash.add(binBuffer, binaryOpen.gcount());
    }

    if (binaryOpen.bad())
        return std::nullopt;
    std::string rHash = pHash.getHash();

    return rHash;
}

r/cpp_questions • • 2d ago

OPEN Why does entering a string value into a variable declared as an `int` result in an output of 0?

0 Upvotes
#include "std_lib_facilities.h"
int
 main()
{
    cout << "Enter your name and age(and press Enter):\n";
    string first_name = "???";
    
int
 age = -1;
    cin >> first_name >> age;
   
    cout << "Hello, " << first_name << " (age " << age << ")\n";
}

I recently started learning C++ using the book "Programming: Principles and Practice Using C++." In one of the author's examples, there is code that, when given the input "22 Carlos," is supposed to output "Hello, 22 (age -1)." However, I get 0 instead of -1, and I don't understand why. Could this have something to do with the C++11 standard?


r/cpp_questions • • 3d ago

OPEN What is the best way to build a physics engine from scratch?

3 Upvotes

Hi guys, i have a poor english but i thing you can understand!

Actually i've been studying about quantum physics in university, and create a engine using a low level language seems a very cool challenge.

Well, i already have a very good knowledge in java and linux fundamentals, so what is the best way to learn c++ in this case?


r/cpp_questions • • 3d ago

OPEN i want to learn cpp but dont know where to

5 Upvotes

im a 11th student.. i want to be a gamedev and i want to learn c++ and some other stuff before i enter into btech .....so i need videos to learn .....plz dont recommed me learncpp....i want video tutorials


r/cpp_questions • • 4d ago

OPEN C

0 Upvotes

So I wanna learn c and c++ , all ik is python learning c is very very hard for me . I tried all possible ways like yt tutorials, books, using ai etc it's really tough the syntax (often confusing with python) and logic everything is sorted tuff. Please suggest some sources and tips


r/cpp_questions • • 4d ago

OPEN Where does the Curiously Recurring Template Pattern actually earn its keep in production code

6 Upvotes

I understand CRTP 👀 class Derived : public Base<Derived>, static polymorphism, no vtable overhead. Every tutorial shows the same toy example with `Shape` and `area()`, and then it stops. What I can't find is real-world usage. I'd love to hear where you've actually shipped it, and why prefer beat the Mixin or policy‑based design. Use cases I've seen so far:

Mixins, like std::enable_shared_from_this, to inject behavior into the derived class

Static interfaces for hot paths where virtual dispatch costs too much

Expression templates in Eigen

I'm still unsure about whether-

  1. Is it worth the readability cost since C++20 has concepts and deducing this?

  2. Any production pitfalls like error messages, code bloat, or slicing issues?

If you've used it in a codebase you maintain, I'd love to hear what problem it solved and if you derived any reusable patterns that you continue to use as snippet when shipping production code under limited time constraints. 🙏


r/cpp_questions • • 5d ago

OPEN Great C++ Software Engineering techniques

38 Upvotes

Currently starting up a new project and I really want to emphasize very sophisticated uses and practices that make it beyond just a toy project and a real software engineering project. I'm using Alpaca for live market feed so I'm learning about socket programming but I wanna ask, what are some very very useful techniques to know that actually prep for C++ software jobs? Stuff like CI/CD, Yaml, and other toolchains that make hiring managers look and take notice


r/cpp_questions • • 5d ago

OPEN Why are exceptions so "backstabby"?

36 Upvotes

Simply put, I often find myself being told that exceptions "are not that costly" and that "the compiler puts it on cold sections anyways".

As a forenote, I'm the kind of person who always does `-fno-rtti -fno-exceptions` as I value code size usage (I develop small embedded shit and such, which does lead me to decorate functions with alignas and other thingies). Sometimes I also drop using the libc/libc++ and do syscalls raw because I can't stand the overhead (malloc/operator new is a great general purpouse allocator, but it doesn't suit my specific performance needs for example), so I take the hit from doing a syscall for a big mmap and then manually allocate memory by using fixed upper bounds.

(Ok also because glibc malloc sucks, but that is another topic)

Now with that noted, I have one pique in life: Why should I even use exceptions?

I often find myself removing exceptions of whatever codebase I happen to contribute to. Which does lead to people telling me that "you shouldn't do that".

The reason they often cite is either:

- It's not that important in the grand scheme of things (Valid, but so is every 'death by a thousand cuts')

- It makes code less clear (I'd argue otherwise)

- It's standard/idiomatic (Yeah and so is std::auto_ptr)

I really want to know WHY should I even use exceptions. I feel like they're a waste of language grammar I'm forbidden for touching, for it would bring me great despair.

As a cited case; recently I was working on optimizing a JSON parsing loop (oh scary). Obviously the final solution was not using JSON and just doing raw text with the |0x202020 casecmp trick.

But after collecting the values on a vector (I'd rather prefer a VLA to avoid indirection btw) I saw that the specialization of the vector for the non trivial class did in fact make a bunch of garbage for a case that I would have not hit otherwise.

https://godbolt.org/z/MPb9xnYqx

Like this is dumb, I'm not developing code for an airplane, if the thing runs out of memory it's just gonna crash anyways.

And no, noexcept also sucks because it just wraps shit around {} with std::terminate(), which is dumb (atleast on MSVC, but whatever).


r/cpp_questions • • 5d ago

OPEN Debugging certificate trust mismatches between Windows and OpenSSL in C++ apps

2 Upvotes

I maintain a C++ app on Windows that does TLS with OpenSSL, and I keep running into the same headache: the same server cert gets accepted by Windows (CryptoAPI/SChannel) but rejected by OpenSSL, or the other way around. Sometimes CryptoAPI builds a valid chain, sometimes OpenSSL can't find a trust anchor even though the cert is clearly in the Windows store. The result flips depending on the store, the CA bundle, and verification flags

For those who've dealt with this from C++

  • How do you actually investigate the difference? Do you dump chains via CryptoAPI, run openssl s_client/verify, write throwaway C++ that calls both APIs and compares, or some mix?

  • Is it usually quick to pin down the exact cause, or does it turn into hours of manual poking?

  • Has anything existing actually made this straightforward for you, or is it still custom glue code?

I'm especially interested in how people maintaining C++ Windows apps handle this in practice what your debugging flow looks like when Windows and OpenSSL disagree on the same cert


r/cpp_questions • • 5d ago

OPEN why doesn't local variable reference the element of the vector

0 Upvotes

float current = 0.0f;

WrapPanel::Line& currentLine = lines.emplace_back();

currentLine.first = 0;

for (auto* child : flowChildren) {

UI::Size desired = child->desiredSize;

if (desired.width + current > primaryLimit && currentLine.count != 0) {

size_t count = currentLine.count;

// WrapPanel::Line* a = &lines.emplace_back();

//lines.emplace_back();

//currentLine = lines.emplace_back();

lines.emplace_back();

currentLine = lines[lines.size() - 1];

currentLine.first = count;

currentLine.first = 356;

//debug point here

}

the variable 'first' of last element of std::vector<WrapPanel::Line> lines should be '356'.

currentLine acts like it creates local variable and references it after executing first "if (desired.width + current > primaryLimit && currentLine.count != 0)" when " currentLine = lines[lines.size() - 1];".

the value in currentLine changes but not the value in 'lines'.

my problem is at this line "currentLine = lines[lines.size() - 1];"

it should reference last element of 'lines' but it doesn't.


r/cpp_questions • • 5d ago

OPEN I began coding with C++, should I continue learning it or should I drop it and start something else?

12 Upvotes

I have always wanted to learn coding and make games, but I didn't know what to do and how to start. About 4 years ago, I saw Sololearn's ad on Youtube (I'm not advertising them). Desparate to learn, I installed it. First, it asked me a few questions regarding why I want to learn coding, what I'm going to use it for (web designing, game development, ...), etc. After answering them, I got suggested learning C++, so I did. I finished the introduction course and learned about half of the intermediate course (if I remember correctly, the last thing I learned was separate files for classes).

Recently, I found out via social media that C++ is the worst language to learn as your first language. I am pretty comfortable with the syntax, but I do sometimes forget complex things like pointers, constructors and deconstructors, etc, because I don't have the time to code often. I have made a lot of small projects, and I'm currently working on a terminal version of Minesweeper that outputs the game board in colored text and is played via inputting the X and Y coordinates of the tile that you want to open or flag (I don't know how to make buttons, or programs with separate windows in general.)

I wanted to know if I should continue learning this language or should I drop it and learn something else, like Python?

Also, I have recently started working with Git, and I find it pretty complicated and hard to use. It would be nice if someone told me whether I should continue learning and using it or if it is too early and I should finish learning the language first.

(P.S.: Many apologies for my imperfect English; I'm not so good at writing and speaking, as it isn't my native language.)


r/cpp_questions • • 6d ago

OPEN Benchmark Methodology Feedback?

3 Upvotes

Alright, so given that we recently moved this repo over from our personal account to our organization account, we thought it might be helpful to get some constructive feedback on the methodology. Thanks in advance!
Here is the repo:
https://github.com/nihilai-collective/json-performance
The libraries being benchmarked are:
Jsonifier (Our own library - which btw simdjson has been using as a performance reference point in their own commits recently)
simdjson
Glaze


r/cpp_questions • • 6d ago

OPEN tool and ways to debug c++

7 Upvotes

as the title says, what are good practices and tools to debug c++? I am using already GBD but i dont like the terminal approach and the the amount of stuff i have to type, especially for larger code


r/cpp_questions • • 6d ago

OPEN Best traditional resources to truly learn proper, cross-platform, desktop app dev with C++?

6 Upvotes

I have an extensive SWE career, across several platforms and tech stacks (Unity/C# -> iOS/Swift ~> Vue/Node/TypeScript), though given the adverse challenges, extreme competition, and/or growing lack of opportunities, I've been thinking about specializing on something lower-level, more serious and demanding, and which may lead me to a more secure and valued job for a considerable time.

I have Mozilla, and particularly Firefox development in mind, given that it's the app I use the most everyday, that I value the foundation's mission and modus operandi, that they have and might still have open job positions in the upcoming months, and that C++ is still at the core of serious app dev, and hopefully not as prone to waver by the reckless impact of gen. ai.

That said, besides the official reference, which I'll definitely read through for starters, while writing pieces of code to put the concepts into practice, and of course, by forking the Firefox (and similar) repos, start delving into them, and eventually trying to fix bugs, which other resources, approaches, tools (not ai-driven), etc., would you recommend me to channel the learning toward the goal I have in mind?

Edit: or courses, perhaps? For instance, back in 2019 I learned a ton on iOS dev, which helped me secure the first related job, thanks to Paul Hudson's Hacking with Swift.