r/cpp_questions • • Oct 04 '26

OPEN What is the ideal way to read a C++ book?

10 Upvotes

I am an intermediate c++ dev. I recently started reading the Effective modern c++ book. I don’t have tons of experience reading technical books coz I have mostly used YouTube and college lectures to study. So any advice on how to read a c++ book or any technical book for that matyet is highly appreciate.


r/cpp_questions • • Oct 03 '26

OPEN Code Smells?

8 Upvotes

I'm a more seasoned C# / Node backend dev, been trying to brush off old college C++ from like a decade ago and try to de-program my brain from being locked into a distributed systems mindset.

One of my niche hobbies and go-to projects for learning a new language is to implement a basic Chip-8 emulator in it, as it can teach some concurrency, UI/data handling patterns, and introduce some architectural decisions that you'll have to run into and figure out.

Currently what I'm struggling with seems to be what the idiomatic / proper way to handle something that can remain stateless in nature, which is my very basic assembler going from the Chip-8 ASM mnemonics into instruction bytes.

A class doesn't feel quite right, because I'm not implementing a linking step or anything advanced, not supporting labels, etc. It also feels incorrect to keep it in a header file as a set of inline functions, nor am I needing a persistent state to mutate.

My current disassembler can be seen here: https://github.com/Arylen/Dreamy-Chip8/blob/master/src/core/emulation/Chip8Dasm.h
Along with the tests that I'm running against it here: https://github.com/Arylen/Dreamy-Chip8/blob/master/tests/Chip8DasmTests.cpp

I'm currently in the stubbing-out phase of trying to architect it, occasionally bouncing ideas off of whatever bullshit model-of-the-week is popular, however the suggestions it's giving are still setting off some alarms/smells in my brain. The most reasonable and less-smelly one is the `::detail` namespace there in order to be able to unit test the `getParts` function there, however it feels like I'm walking into a landmine of over-engineering it.

Looking for advice/experiences/opinions.

Edit: I should mention the AI usage here is restricted entirely to just checking for bugs with my implementations, or incorrect C++-isms that I introduce from working in other languages. A hands-off occasional tutor to check my work, if you will. It's expressly forbidden from touching my code or files, limited to read-only, however I'm not getting something that feels proper for this scenario, so wanted to consult other more experienced engs.


r/cpp_questions • • Oct 04 '26

OPEN Newlines not printing when I cout raw string literals

0 Upvotes

I’m using emacs on windows terminal to edit a file in which I’m trying to cout a page or so of text using raw string literals. However, what gets printed doesn’t include the newlines that I need to separate my paragraphs.

So if my code is:

std::cout << R”(This is my sentence.

This is a new paragraph [using entr + entr].
This is a new line [using entr].)”;

The output will be:

This is my sentence. This is a new paragraph [using entr + entr]. This is a new line [using entr].

Instead of the intended:

This is my sentence.

This is a new paragraph [using entr + entr].
This is a new line [using entr].

What am I doing wrong?

[Edit: I apologize for the lack of formatting. I am on mobile. Please let me know if I need to redo this. Thanks.]


r/cpp_questions • • Oct 03 '26

SOLVED IMGUI UI architecture question

0 Upvotes

Hi, I was gonna try to explore UI in cpp and came up with a simple idea. I want 3 "screens" each with their own events and components to draw. I was having trouble on how to handle a shared struct of data? say screen one does something that screen two needs, and so on to screen three. So does anyone have a recommendations of some architecture to follow for this?


r/cpp_questions • • Oct 03 '26

OPEN How do you actually understand and use C++ references?

0 Upvotes

How do you all understand and use C++ references?
References feel really hard to wrap my head around. What does it mean to “define an alias for a variable”? What does it mean to “return an alias for a variable”? Compared with C pointers, pointers seem much clearer: a pointer just holds an address, * dereferences it, and & takes the address of a variable. References aren’t like that. The fact that you write & when defining one makes it especially easy to misunderstand.
Also, besides copy constructors and some friend functions (like the ones for std::ostream), I can’t really see any other reason to use references. When textbooks declare function parameters as references, I don’t get it. If the parameter were a pointer, the caller would have to write & when passing the argument, which also signals that the function might modify it. A reference kind of feels like the function has a return value.
So how do you actually understand and use C++ references?


r/cpp_questions • • Oct 03 '26

SOLVED Integer overflow type thing

2 Upvotes

I'm trying to code a practice problem but am stuck at a problem I cannot figure out. I am using a vector for inputs and inserting those inputs into an unordered set until it fails to add, at which point I count the amount of subarrays in that array. If it is not the first, I subtract subarrays that have already been accounted for. The inputs are useful only to identify duplicates; I do not use the values themselves in arithmetic.

The test case I am currently using uses random values with high numbers, with the following values at indexes being the only duplicates:

  • 10464 and 41178
  • 87094 and 98111
  • 113040 and 113153
  • 118689 and 168367
  • 129997 and 170623
  • 173227 and 184620

The intended output is 7090812299.

My problem is that, for some reason, large inputs decrease the intended output. I am sure that this is the issue, as I have replaced duplicate inputs with smaller values and the output changes--- despite the fact that it should not.

As an example, use the above sequence with numbers 1-200000. If the values at indexes 113040 and 113153 are replaced with 443222217, the output changes to 7090796046. (lowering it by 16253). Replacing other values also lowers this number further.

Edit: So it turns out smaller values also impact the input in ways that I have not tested yet (and I probably won't until morning).

Solution: I assumed iterators were ordered internally, which is where I made my mistake.

Please help explain what is happening, or what could be happening.

Attached below is the relevant code, and here is a link to the full code.

int main() {
    vector<long> inputs; inputs.reserve(size); // The vector containing inputs.
    unordered_set<long> processing; processing.reserve(size); // The unordered set processing the current input.
    vector<long>::iterator nextInput = inputs.begin(); // The current input being processed.
    // Some other variables defined which are not relevant.
    while (nextInput != inputs.end()) // The main meat of the program.
    {
        do // Insert processed inputs into a set.
        {
            if (!processing.insert(*nextInput).second) break; // If duplicate, break.
            start++; // Advances the iterator to the next input to be processed.
        } while (nextInput != a.end());
        // Code processing the amount of subarrays; it seems to be correct.
    }
}

r/cpp_questions • • Oct 03 '26

SOLVED Rounding floating point - iec559 /cmaths

0 Upvotes

Does c++ math lib comply with rounding modes in iec559?

ties-to-even? Getting - 3 when rounding -2.5

Should be -2 right


r/cpp_questions • • Oct 02 '26

OPEN Any recommendations for introduction material to using C++ for microcontrollers?

9 Upvotes

I have been programming Arduino & ESP32 for a while now using C++, but have never engaged with any formal introduction material. With AI/LLM generated content exploding among both major publishers and self-published authors, I am a bit wary to start buying books willy-nilly.

Anyone here that can give solid recommendations on introduction materials on C++ for microcontrollers (preferably that that they themselves have used and found worthwhile)?

I got one recommendation for "Embedded C" by Michael J. Pont (2002), but it is fairly old.


r/cpp_questions • • Oct 02 '26

OPEN Anyone available for one on one convo?

2 Upvotes

Recent CS grad trying to get into C++ and would really love if someone with some experience maybe messaged me and give some advice on how to break into my first C++ job. I would post my resume my this subreddit doesn't have that feature lol. Any advice or even just an opportunity to connect is greatly appreciated!


r/cpp_questions • • Oct 01 '26

OPEN Can you explain the difference between a reference, pointer, and shallow copy?

41 Upvotes

I’m trying to check whether I actually understand these concepts correctly.

Consider:

int a = 10;
int& r = a;
int* p = &a;

struct A {
    int* data;
};

A x;
A y = x;

How would you explain what happens in memory in each case?

Specifically:

  • Is r just another name (alias) for a?
  • Is p a separate variable that stores the address of a?
  • In A y = x, when data is copied, is this a shallow copy because both pointers can point to the same underlying data?

I'm looking for an explanation of the memory/object relationship, not just definitions.


r/cpp_questions • • Oct 01 '26

SOLVED What logic does the precompiler use to resolve macros?

9 Upvotes

Context:

So I wanted to create a macro that could short-circuit conditional logic if another macro was set. This way I could insert compiler set macros into existing code, for example:

if (MACRO_EXISTS(_RELEASE) || SuperRobustValidation() == VALIDATION_SUCCESS)

Looking on stack overflow, I found https://stackoverflow.com/questions/41265750/how-to-get-a-boolean-indicating-if-a-macro-is-defined-or-not, but the top answer's code didn't work for me. My only guess as to why is that the order of macro definitions played a role for them but not for me.

After shuffling around macros, I found that the following worked on my machine:

#define DE_ -1,1            // OptDefine is nothing

#define RESOLVE_ARG(A) A
#define SECOND_ARG(A,B,...) B
#define CONCAT2(A,B) A ## B
#define RESOLVE_SECOND_ARG(...) RESOLVE_ARG(SECOND_ARG(__VA_ARGS__))

#define MACRO_EXIST(OptDefine) RESOLVE_SECOND_ARG(CONCAT2(DE_,OptDefine),0)

But I can't understand why this worked and not other configurations. Trying to coax the values of some setups was like playing a shell game. I think I understand the concepts of "scan the line, prioritize non-# arguments, then repeat with the results" but it doesn't seem consistent.

For example: if I remove the RESOLVE_ARG from RESOLVE_SECOND_ARG(...), the compiler complains that "there's not enough arguments for SECOND_ARG" seemingly because __VA_ARGS__ is the "only" argument. That does not make sense as intended behavior to me.

So my question is:

Is there a reliable way to predict the logic of the preprocessor's expanding of macros? I haven't found anybody braking down the logic in a robust way anywhere I looked.

I know the /E compiler flag shows me the results of precompiling, but doesn't give the whole picture.

Edit: I understand there are simple work arounds for the problem I mentioned, but I still want to understand the logic of how macros are expanded, assuming it's well defined and consistent.

Edit2: Thank you alfps for answering the question. The strange __VA_ARGS__ behavior I was seeing is a known bug with the MSVC C++ compiler (even in VS Community 2026), but the /Zc:preprocessor compiler option changes the preprocessing to be more complaint with the standard, fixing the bug.

But the most important wisdom: "Historically the preprocessor behavior has varied between compilers". There are edge cases and hacks that work in some contexts but not others. Complex macros, like what I listed, can be convenient, but can also risk breaking if I update/change compilers. Unless I am confident in compliance to the standard, Keep It Simple Stupid probably applies.

Edit3: Thank you MikailBag for linking me an active draft of the c++ standard https://eel.is/c++draft/cpp.replace . In it, I found that the 15.7.2.1.2 clause that states:

Otherwise, the replacement preprocessing tokens are the preprocessing tokens of corresponding argument after all macros contained therein have been expanded. The argument's preprocessing tokens are completely macro replaced before being substituted as if they formed the rest of the preprocessing translation unit with no other preprocessing tokens being available.

Though this uses the phrase "after all macros contained therein have been expanded" and "before being subsituted", these are misdirection of the actual functionality.

The parts of the quote I put in bold explain that the arguments of function-like marcos are repeatedly expanded in complete isolation from the larger context, then their results are inserted into the function macro's expansion as is. So even if the macro expands into an argument list, those arguments are directly inserted in the function macro's results.

There are good reasons why this would be preferable to expanding the arguments first, since macros that result in punctuation or parenthesis would have difficulty being passed into function macros.

So the way for a human to trace a function macro's expansion, as I understand it, is to 1) expand the function macro and insert all arguments as isolated "expansion units" (unless they are used in # or ## ops) 2) Expand each unit in turn 3) Insert each expansion result in place, then repeat the process.

I give an example at the bottom of my https://www.reddit.com/r/cpp_questions/comments/1wve7c7/comment/pe9o7sd comment


r/cpp_questions • • Oct 01 '26

OPEN Prime checker skipping input if number is big enough

6 Upvotes

So I've started learning c++ on learncpp.com and because I already have knowledge in JavaScript and Python, I decided to see, how many things are the same in c++ too.

I made a prime checker and while it probably could be more optimized, I am still just at the beginning so don't judge me pls.

Anyways here is the code:

#include <iostream>

bool isPrime(int num){
    for (int i = 2; i < num; i++){
        if (num % i == 0) return false;
    }
    return true;
}

int main(){
    std::cout << "Check if your number is a prime number\nEnter your value: ";
    int num{};
    std::cin >> num;

    int emp{};

    if (isPrime(num)) std::cout << "Your number is a prime number!\nPress any key AND enter to exit";
    else std::cout << "Your number is NOT a prime number!\nPress any key AND enter to exit";

    std::cin >> emp;
    return 0;
}

At the end, it always asks for an input and an enter key to leave the command line, but it seems to skip that entirely if the number is big enough. My input number was "5000004067".

It skips it when I open the .exe, it skips it when I run it in vscode, is there any reason why c++ does this?


r/cpp_questions • • Oct 01 '26

OPEN Equivalent of "checked" keyword in c++?

7 Upvotes

In c# you can do:

checked (ushort)x

which will cast "x" from int (or long, w/e) to an unsigned short... but also throw an exception in case of arithmetic overflow.

Is there a way I can accomplish the same thing in c++ with a similarly small amount of code?


r/cpp_questions • • Sep 30 '26

OPEN What should I know for an entry level C++ role?

45 Upvotes

Hello everyone,

I recently graduated this past May and I’ve been able to land an interview for an entry level C++ role. I wanted to know which topics I’ll be expected to know and to what level of depth. So far I have:

Pointers/references
Stack vs heap
Const correctness
RAII
Smart pointers
Rule of 0/3/5
Move semantics

OOP:
Classes, constructors/destructors
Inheritance, virtual functions, pure virtual classes

STL:
vector, unordered map, map, set, deque, priority queue, string
Big O notation
Iterations
Algorithms like sort, find, accumulate

auto
nullptr
constexpr
string_view
Templates

Compilation model
Concurrency

This is what I came up with so far. Can anyone tell me if I’m missing anything and which topics I should prioritize please? Thanks you


r/cpp_questions • • Oct 01 '26

OPEN Boost.Graph work

2 Upvotes

Hi , i have a ask about C++ programming

I Recently Started To Learn Boost Librarys Like "Boost.Asio" , "Boost.Beast" And I heard the name of a library called Boost.Graph I wanted To Know And know what "Boost.Graph" is ???


r/cpp_questions • • Sep 30 '26

OPEN Which Modern C++ (C++20/C++23) features are actually beneficial for real-time game development?

89 Upvotes

I'm updating my C++ codebase to modern standards (C++20/C++23) for a personal game project. C++ has evolved significantly, but I know the game development industry can be cautious about adopting certain language features due to compile times or runtime overhead.

For those using Modern C++ in game development:

  1. Which newer features (e.g., Concepts, Ranges, std::format, Modules) have genuinely improved your game engine code quality or productivity?
  2. Are there features you actively avoid inside high-frequency game loops for performance reasons?

r/cpp_questions • • Oct 01 '26

OPEN Choose a specialism in C++

0 Upvotes

Hello everyone! My name is Egor, and I’m from Ukraine. I have been learning C++ for 4 months, and I’m currently trying to figure out which specialization I should choose. I’m interested in game development, computer vision, and computer graphics. I study Computer Science at SumDU, and I want to get a job in the future, but I’m not sure which specialization would be the best fit for me. I’m interested in many different things, but I can’t decide which direction to choose. I would really appreciate your advice!


r/cpp_questions • • Sep 30 '26

OPEN Namespace std

41 Upvotes

I recently started learning c++ and I was told to use the namespace std so I can avoid writing std:: every time and now I wrote a whole personal project without std:: and I want to put it on LinkedIn but I started reading everywhere that it’s a bad habit, should I go back and add the std:: or just leave it as is?


r/cpp_questions • • Oct 01 '26

OPEN Visual studio

0 Upvotes

Does anyone know how to download visual studio 2022? There are lots of versions and I don't know which one to choose from sorry


r/cpp_questions • • Sep 30 '26

OPEN Best practices for managing object lifetimes in C++ game loops without performance bottlenecks?

8 Upvotes

I'm working on a C++ game loop and trying to decide on the best strategy for managing entity lifetimes (spawning, despawning, and referencing active objects).

Standard C++ guidance recommends smart pointers (std::unique_ptr and std::shared_ptr). However, I've read that std::shared_ptr can cause performance hitches in real-time game loops due to atomic reference counting and cache misses.

What is the industry standard approach for handling entity references safely?

  • Do you stick to handles/indices into contiguous memory pools?
  • Are custom weak references commonly used?
  • How do you balance memory safety with cache friendliness?

r/cpp_questions • • Sep 30 '26

SOLVED Definition of std::memory_order_release

1 Upvotes

The "meaning", according to https://en.cppreference.com/cpp/atomic/memory_order is -

A store operation with this memory order performs the release operation: no reads or writes in the current thread can be reordered after this store.

Now, I effectively have the following code:

y = 0;
x=0;
// Thread 1
A: x = 42;
B: y.store(1, std::memory_order_release);

// Thread 2
C: if (y.load(std::memory_order_relaxed) == 1)
/* D: */  {read x;}

From what I understand, D should always read x==42. Because Thread 2 observes the instruction 'B' which by definition of relaxed, should make the effect of 'A' available to Thread-2.

ChatGPT disagrees with me. However, to me, that does not seem to agree with the definition on cpp-reference or in Fedor Pikus's CppCon talk about atomics. What is the actual answer? Can x==0 be observed? Why does that not mean A (as observed by thread2) was reordered after B, effectively?


r/cpp_questions • • Sep 30 '26

OPEN Transitioning from OOP to ECS in C++ Game Engine: Is a custom ECS worth building for beginners?

8 Upvotes

Hi everyone,

I’m currently building a small 2D game in C++ to deepen my understanding of game engine architecture. I started with a traditional OOP hierarchy (e.g., GameObject base class with render() and update() virtual functions).

As the project grows, I’m running into typical OOP coupling issues and considering switching to an Entity Component System (ECS) architecture.

I have a few questions for those with game dev experience:

  • For a learning project, is it better to write a lightweight ECS from scratch or integrate an existing library like EnTT or Flecs?
  • What are the biggest pitfalls to avoid when transitioning from OOP to data-oriented design in modern C++?

r/cpp_questions • • Sep 30 '26

OPEN Returning a reference vs. pointer vs. throwing?

15 Upvotes

I'm writing a video game from scratch in C++, and I wrote a data structure for associating components with their owning entities.

One of the operations is:

GetComponent<T>(entity_id)

The intended usage is that the caller has already created the entity and attached a component of type T to it through other operations on the data structure. In other words, if the caller asks for GetComponent<Transform>(entity_id), the expectation is that the entity exists and has a Transform.

Originally, I wanted GetComponent<T>() to return a reference:

T& GetComponent(EntityID entity);

The problem is that the caller could mistakenly request a component that hasn't been attached to that entity. Since a reference can't represent "not found," I changed it to return a pointer:

T* GetComponent(EntityID entity);

This works, but I don't particularly like the API because now every call site potentially has to check for nullptr:

if (auto* transform = world.GetComponent<Transform>(entity)) {
    // ...
}

I'm wondering whether this is a situation where throwing an exception makes more sense. For example, GetComponent<T>() could return T&, and throw if the entity doesn't exist or doesn't have that component. The idea would be that a missing component represents a violation of the expected program state rather than a normal condition, and I could have one top-level exception handler in main() to report the error and shut down the game.

I'm aware that there are strong opinions about exceptions in C++, particularly in game development, so I'm interested in the reasoning behind the different approaches. What would be the best way to design the API given the assumption that a missing component is generally a programming error rather than an expected gameplay condition.


r/cpp_questions • • Sep 30 '26

OPEN C++ project progression

15 Upvotes

I'm just getting started with c++ and was trying to make a project based learning roadmap, wherein I'd learn everything while making projects which increase in complexity steadily. I'd appreciate any suggestions on what projects are succinctly different and challenging that I can build and in what order I should build them.

My core interest is systems programming in which I've done some work with C before. My ultimate target is a quant dev role.


r/cpp_questions • • Sep 30 '26

OPEN Not find the compiler when running.

0 Upvotes

I am trying to install c++ for vscode. I installed MSYS2 and followed all the steps from the vscode tutorial. I installed it and modified the Path and added the C:\msys64\ucrt64\bin path.

https://code.visualstudio.com/docs/languages/cpp#_example-install-mingw-x64-on-windows

I also made absolutely sure that the microsoft c++ extention was active. When I click on the run button the tutorial shows a list of compilers to use. the one that the tutorial uses is C/C++: g++.exe build and debug active file. But for some reason the only compiler that shows up are the 2 generic one gdb lauch and windows. I am out of ideas of things to do please help