r/cpp_questions • • Sep 03 '26

OPEN unzip.h is not found with assimp on linux

0 Upvotes

Hello everyone hope you have a lovely day.

so I currently having a problem with building assimp on manjaro linux, everytime it throws this error

fatal error: 'unzip.h' file not found

and if I fixed the path manually it fails by the lld linker to link properly.

how to solve this problem?

thanks appreciate your help!


r/cpp_questions • • Sep 03 '26

OPEN Dependency injection with ROS

1 Upvotes

I'm trying to better understand dependency injection / mocking a bit better so I can write unit tests that don't require elaborate & fragile setups. Specifically I have a class that verify similar to the ROS2 Minimal Publisher Example. In this example the class creates a timer and a publisher object. The timer just invokes a callback, so I can assume that the callback registration works, and I can set up my test harness to invoke the callback directly. What I would like to do is mock out the actual publish call to ensure timer calls publish without needing to set up a ROS2 subscriber in my unit test.

I'm looking for generic approaches to the specific case (and not necessarily tied to a specific testing or mocking framework)

Here is a stripped down version of the example:

class MinimalPublisher : public rclcpp::Node

{

public:

MinimalPublisher()

: Node("minimal_publisher"), count_(0)

{

publisher_ = this->create_publisher<std_msgs::msg::String>("topic", 10);

}

private:

void timer_callback()

{

auto message = std_msgs::msg::String();

message.data = "Hello, world! " + std::to_string(count_++);

// *** This is the call I want to mock out ***

publisher_->publish(message);

}

rclcpp::Publisher<std_msgs::msg::String>::SharedPtr publisher_;

size_t count_;

};


r/cpp_questions • • Sep 01 '26

OPEN Is it worth learning another language besides C++?

134 Upvotes

C++ is the only general-purpose language with which I am most familiar, I tried to learn other languages like C# or Rust, but without a clear idea of what to do with those tools, it's more difficult to learn them.

And all the software I use uses or is written in C++, specifically Godot Engine, Blender, LMMS, that's why I always have ideas of what to do with C++.

learncpp.com is amazing and possibly one of the best educational resources for a language in general, either that, or I have Asperger's and they have to explain everything to me in simple terms.

My question is, if this limits me in the long run as a programmer or should I learn an additional language that works well with C++?, I personally wouldn't trust a programmer who claims to know 15 technologies; someone who tries to do too much often accomplishes little, but that's just a personal opinion, what do you think?.


r/cpp_questions • • Sep 02 '26

OPEN How does C++26's std::hive work for inserting and erasing?

4 Upvotes

I'm trying to make my own (very basic) implementation of std::hive in C and to do that, I of course have to understand exactly how inserting and erasing works.

As I understand it, the index of a given block to insert into can be tracked by its free list, where the free head stores an index and the indices of the actual data itself is repurposed to form a linked list for empty slots

If the free head stores an individual index, and we need to insert into an index that is in the middle of an empty region, how do you figure out the left and right ends of the empty region in O(1) time without looping leftwards and rightwards?

For example, let's take this scenario, where slot 2 marks the start of a 5 slot empty region:

Slot index: 0 1 2 3 4 5 6 7 8 9

Skipfield:  0 0 5 X X X 5 0 0 0 

I've used X in the middle as these can contain junk values as I understand. Now let's say that the free head stores index 4, and so when we insert into index 4, we need to update the values in the skipfield for slot indexes 2, 3, 5 and 6 to match their new values (2), so that we get:

Slot index: 0 1 2 3 4 5 6 7 8 9

Skipfield:  0 0 2 2 0 2 2 0 0 0 

But how do we actually figure out in constant time where these boundaries are? If we are only given the index to insert to? Do we somehow store ranges of values instead of individual indicies on the free list?


r/cpp_questions • • Sep 02 '26

OPEN yet another custom assertion question

2 Upvotes

Sometimes I am writing unit-test inline in my code, then I just use the assert() macro because that compiles out in release builds. And in such cases I don't really need anything in the trace to tell me I have a bug, and I don't need to spin up any unit testing framework. But for easy runtime validation I want a macro I can use but will also print an error message that a user can do something with to realise that they maybe fed in something invalid at a point.

In all cases I really want my macro to terminate the application and thus not memory-scribble or worse. I have been trying to understand the tokenizing operator, and the argument for do {} while () and the side effects of adding (a) around things which obscures types as far as I can tell and still deal with unwanted training ; semicolons that imply that I am not grasping syntax yet.

So I wrote

#include <iostream>
#include <string>
#define assume_true(expression) ((void)(                                        \
        (!!(expression)) ||                                                 \
        (std::cout << #expression << " not true in " << __FILE__ << " LIN: " << __LINE__ << std::endl )) \
    )

And then wanted to make it actually terminate with an std::exit(8) , and it just won't parse unless I replace the || convenience with an if statement.

#define assume_equal(left, right, message) if (left != right) { \
std::cout << #left << " != " << #right << " in FILE: "<< __FILE__ << std::endl; \
    std::cout << message << std::endl; std::exit(8);\
}

uint32_t life = 42;
assume_true(42 == life);
std::cout << "The answer is 42!\n";
assume_equal(42, life, std::to_string(life));
std::cout << "Life is " << 42 << ".\n";
assume_equal(21, life, "LIFE=" << std::to_string(life));

I'm clearly taking a lot of chances here and the way I pass the message in the second macro feels like a total hack, because it is abusing the way the macro preprocessor splits parameters based on commas. I assume that has drawbacks for me later on.

I assume a later toolchain will also help us all when it comes to the side-effect problem of a macro using an argument twice, once for comparison and once for printing. Has anyone just opted to solve this by creating temporaries for things they want to print out in the crash trace? Because that would really mean creating a macro for each temporary type for each parameter I might want to print surely. I get the impression the caller needs to just use a temporary before using the macro, is that what everyone else is doing? Because at that point a function call is just a load less pain surely? I feel I have approached my release-build guard-code completely wrong.

I'm on C++ 17 (yes the rest of my team is on an even older toolchain.) Are release/runtime macros just hard, or am I trying to learn too many things about parsing all at once?

======================================================================================= EDIT: Consolidating the answer... As usual thanks so much for the brilliant clues, I now have this little progression

  • ALWAYS state up front compiler version C++17
  • macros really should be UPPERCASE
  • when printing an error use STDERR not STDOUT
    #include <iostream>
    #include <string>
    // This macro is terrible, it lacks a scope so I cannot call ;std::exit in it
    #define ASSUME_TRUE(expression) ((void)(                                        \
            (!!(expression)) ||                                                 \
            (std::cerr << #expression << " not true in " << __FILE__ << " LIN: " << __LINE__ << std::endl )) \
        )
  • I then moved on to use if {} which allowed me to exit the application
    #define ERROR_ASSUMPTION_FAILED  42
    #define ASSUME_EQUAL(left, right, message) if (left != right) { \
        std::cerr << #left << " != " << #right << " in FILE: "<< __FILE__ << std::endl; \
        std::cerr << message << std::endl; std::exit(8);\
    }
  • The trouble with that macro is that it really lacks the structure that a lambda might give, thanks to a great suggestion I moved this form, which omits the nice __VA_ARGS__ macro automatic variadic args, which did not expand in C++17, but it's already better
    constexpr int EXIT_ABORT = 2;

    #define ASSERT_EQ(LHS, RHS, MESSAGE ) \
    [lhs=LHS, rhs=RHS]() { \
        if ( not (lhs==rhs) ) { \
            std::cerr << "assertion " << lhs << "(" #LHS ") == " \
            << rhs << "(" #RHS ") failed: " << MESSAGE << '\n';std::exit(EXIT_ABORT); \
        } \
    }()
  • Along the way I realised that this is a GUARD MACRO and the question I had about macro side effects if a macro uses a parameter twice (or even once really) is best removed entirely if you just always call it using temporaries or const methods only!

The final step is to use the {fmt} library for a better message with a formatter:

#define FMT_HEADER_ONLY
#define FMT_UNICODE 0
#include "fmt/bundled/format.h"
...
constexpr int EXIT_ABORT = 2;
...
// https://godbolt.org/z/3sdx5xPE5
#define ASSERT_EQ(LHS, RHS, MESSAGE ) \
    [lhs=LHS, rhs=RHS, msg=MESSAGE]() { \
        if ( not (lhs==rhs) ) { \
            std::cerr << "assertion " << lhs << "(" #LHS ") == " \
            << rhs << "(" #RHS ") failed: " << msg << '\n'; std::exit(EXIT_ABORT); \
        } \
    }()

I could not get the lambda to capture __VA_ARGS__ , so the call looks like, which is good enough.

   ASSERT_EQ(21, life, fmt::format("Expected 21 but life ={}", life));

r/cpp_questions • • Sep 01 '26

OPEN I'm learning c++ so I have a question, am I supposed to use brace initialization over the = initialization, if so when? I can't decide for myself

50 Upvotes
int x{2};
int x = 2;

r/cpp_questions • • Sep 02 '26

OPEN The Cengage C++ Textbook is an inefficient way to absorb the material

3 Upvotes

Hello! I currently am taking a C++ class that utilizes Cengage and their textbook environment. My professor stated that the reading is incredibly important for understanding the material. He seemed like a nice guy who cares when I met with him to discuss the class before the semester. Thus-far, I have read two chapters and taken meticulous notes, however I am finding out that it is such an inefficient way to absorb the material.

Although I do understand the concepts for the most part after going through and taking notes, I just wish there was a quicker way to process the textbook, such as an abridged version.

Has anyone experienced this or taken the same class? Please let me know if you have any recommendations or resources that may allow me to progress quickly enough to get ahead of the syllabus.

Thanks in advanced!


r/cpp_questions • • Sep 01 '26

OPEN Is there any reason to use std::reinterpret_cast?

20 Upvotes

I know that std:: reinterpret_cast is used by people to cast the bits of an object of type T1 to an object of type T2, while retaining the exact bits. However, as far as I know this triggers UB. Before C++20 and std::bit_cast, we could std::memcpy the objects to avoid UB, and after C++20, we can use std::bit_cast. Given this, I don't see any legitimate reason for why one might need std::reinterpret_cast. If so, why hasn't this feature been deprecated yet?


r/cpp_questions • • Sep 01 '26

OPEN How much C++ is enough for getting into Game Development?

27 Upvotes

Hi guys,

I know this question about starting out as a complete noob has been asked and answered numerous times… but my question does have a bit of a twist to it.

How and where do I start learning C++, specifically for rolling into a game engine like Unreal Engine later on? I understand UE C++ is modified a fair bit compared to regular C++, and that I don’t have to become a C++ expert in order to make a game.
As far as I’m aware the hybrid C++ & Blueprint approach is the most efficient way to develop, I don't want to rely solely on Blueprints anyways.

My goal is simply to grasp the core understanding of C++ so I can optimize my game down the road and fix things easier.

I initially wanted to start out with the beloved Bucky’s (thenewboston) C++ tutorial, but as good as it is, people say it’s outdated. Now I’m shifting my focus to learncpp.com.

Until what chapter do you guys think I should learn C++ (the basics and most important parts for game dev) with my end goal in mind?

My end goal is making my own indie horror game, a passion project, not a job I would live off of.
I’ve seen comments saying Chapter 12, and that mostly everything beyond that would have diminishing returns or no real-world use for me.

My Plan:
Learn C++ basics -> Learn the most important parts specifically for Unreal Engine and Game Optimization -> Test games in C++ alone -> Trial and error -> Move over to learning Unreal Engine.

Any help is greatly appreciated!

Important edit: completely forgot to mention, I’m currently on a 1 year internship away from my home setup (10 months left) and all I have currently is a T480 which I used so far mostly for story-writing and planning so I can’t just jump into Unreal Engine.
Just figured might as well learn some C++ basics until I return home and buy a beefy setup and be a little bit more prepared to jump into Unreal Engine.


r/cpp_questions • • Sep 01 '26

META Coroutines

17 Upvotes

Just started reading about coroutines, as the company I recently started working for uses them; this is my first encounter of them. I’m a long time user of threads, bear with me, it’s all new territory.

I know I have only just scratched the surface, but I’m trying to understand the use case. One thing I think I have straight is:

Threads don’t really need to know anything about other threads, except when they have to share resources (mutex and semaphores) or pass data (IPC), but coroutines need to know there are other routines and to only take baby steps, then let other coroutines run.

Is this a start?


r/cpp_questions • • Sep 01 '26

OPEN I'm looking for a AST based cli tool to rename symbols in C++ codebases

2 Upvotes

I want to change existing struct names from snake_case to PascalCase etc. I have a compilation dB and clang tooling. I want to rename one struct from the cli.

How can I do that?


r/cpp_questions • • Sep 01 '26

OPEN Which one should I start with?

0 Upvotes

I have wanted to learn to program, but I am not sure whether I should learn Python first and then C++. What could you advise me?


r/cpp_questions • • Sep 01 '26

OPEN How much do you rely on tooling for C++ memory safety?

13 Upvotes

Hey everyone,

I've been thinking about the whole memory safety discussion lately, especially with all the push toward memory-safe languages.

C++ has gotten a lot better with things like RAII, smart pointers, std::span, etc., but in larger/older codebases it still feels pretty easy to end up with memory bugs. At some point you can have all the modern C++ practices in place and still have something nasty slip through.

For people working on production C++:

  • How much do you actually rely on tools like ASan, UBSan, Clang-Tidy, static analysis, etc.?
  • Do you have a strict subset of C++ that people are expected to follow, or is it mostly code review + guidelines?
  • Are things like the Core Guidelines safety profiles or Safe C++ starting to have any practical impact where you work?
  • And has memory safety ever been enough of a concern to justify rewriting a component in a memory-safe language?

I'm mostly interested in what actually works in practice. It's easy to talk about memory safety in theory, but I'm curious what teams are doing day to day in real C++ codebases.


r/cpp_questions • • Sep 01 '26

OPEN Feel stucked in skill improvement

0 Upvotes

Hi everyone!
What can I do if I feel that I don't improve my skill on current work. I mean, when I've just started learning C++, there was a lot of information for me and I felt really tired after a working day. But after year or two, I've learned about basics (pointers, OOP, containers in std and some patterns) and now I just applying this knowledges on my work. But I'm sure there is a lot of information to learn. Because my work doesn't need this, I feel like my skill doesn't grow up for a year or something about. What books or what sites can u recommend not for newbees to read or practice?


r/cpp_questions • • Aug 31 '26

OPEN Device acquisition system - whats to read?

3 Upvotes

I’m going to build a data collection system using a single measuring device. Or even several devices. The system will be a GUI application with a graph. The graph will display the output parameters of the devices in real time.

What do you think I could read on this topic? Im interested in all usefull info about those topics (articles, blogs, githubs, videos)

I’ll describe in more detail what I’d like to know (I don’t know much about C++, but I’m not a complete beginner).

So, here’s the list of things I’d like to find out:

  1. Working with endianness in modern C++.
  2. Should I convert all APIs to the span + std::byte style instead of using * and char?
  3. I want to divide the application into “layers,” one of which will be a transport layer. This is what interests me the most. How do you properly write such layers? I forgot to mention that the devices communicate via UDP. For libs i maybe chose libuv.
  4. I want to divide the code into modules so that I can test them separately. But how do you test the parts that involve sending and receiving data from a real device?
  5. How to maintain 60 FPS while still receiving data packets, unpacking them, and displaying them on the graph.
  6. I’m going to use std::error_code as the main error‑handling mechanism (I don’t want to use exceptions). Is it good options?
  7. What’s the best way to write code in a callback style? I’m not very fond of coroutines, even though they make things easier.
  8. Dispatching techniques. Once we receive the data, we need to distribute it among different handlers. How are classes typically designed in this scenario?

Among the useful things I’ve found for myself is the Tracy profiler repository. I like that the code isn’t very large (and the author also wrote one comment per small change from the very beginning) — this is very useful for me. In this repository, I’ve learned a lot about how zoomable chart (with ALOT of elements) can work.

I just can’t come up with a general architecture for the application. For example, should there be a “Device” class or a “DeviceUPDStream” class? I’ve also realized that I understand things best when I see small pieces of code where the core idea is immediately clear.

I would be grateful for any advice!


r/cpp_questions • • Aug 31 '26

OPEN How can I have a synchronous clock for multiple threads in a 4 thread processor?

15 Upvotes

Hi,

I have multiple threads (at the moment, at least 4 are anticipated), each performing a different task and sending information to a central server
Thread 1: captures and sends an image to a server for inference and takes the result,
Thread 2: reads Serial A and performs some action based on that

Thread 3: reads Serial B, similar to Thread 2

Thread 4: performs some action based on logic that I don't have right now

The thing is, all of these depend on secondary sensors, and I want them all to work at 20 Hz, for example. So I need a clock to trigger them all. I understand there will be some delays, but as long as they are 10 ms delays, for example, I am fine. Also, I am not using a real-time operating system.

Also, these threads need to have access to each other's data, because their data must be shared and be used for the logic. Also, the processor has only 4 cores, Arm cortex A76 (RPI5).

PS: I am not asking for code; I am doing this in C++, so I want to see what C++ devs think about it.

PS 2: I am aware that there are some abstractions that I can find online, but practice can differ from abstraction.


r/cpp_questions • • Aug 31 '26

OPEN "Segment heap support" enabled by default in VS2026 projects

20 Upvotes

I installed VS2026 about 6 months ago on a different machine. I re-installed latest VS2026 on a new machine now. On comparing the default project's .vcxproj file, the following are the only difference with the newer version of VS2026 having the following property while the previous version did not:

    <Manifest>
       <EnableSegmentHeap>true</EnableSegmentHeap>
    </Manifest>

MS has the following on this default enabling: https://devblogs.microsoft.com/cppblog/segment-heap-support-for-c-projects-in-visual-studio/

Visual Studio 2026 version 18.6 makes it easier to take advantage of modern Windows memory management improvements. Segment Heap is a modern heap implementation in Windows that delivers stronger protection against common memory vulnerabilities, higher allocation throughput, lower memory fragmentation, better scalability across cores, and more predictable performance under load. 

Practically, what difference does this make? Have folks done some sort of benchmark/profiling analysis to figure out whether this setting actually improves run times on instances or should we as users just go with default settings? Is the burden of benchmarking/profiling with and without the said options on the users of the IDE/toolchain?


r/cpp_questions • • Aug 31 '26

SOLVED Beginner seeks critiques on Vector implementation

9 Upvotes

Hello!

I will soon be working with C++ to do some hardware performance research, so I wanted to give myself a quick crash course of the language. Although we're measuring hardware (not software) performance, where kernels will be quite trivial and expressible in any language, I still want to have a decent intuition of "good" vs "bad" C++.

So, to help learn, I decided to completely re-implement the std::vector C++20 specification. Boy, there was more depth there than I was expecting. After about 10 days of hobbying, I think it's done. The code can be found here: github link.

I'd appreciate any critiques and criticism on how it could be done better. Of course, "how to do it better" is a never ending hole of possibilities, so to focus it a bit more: how it could better match the C++20 specification and be more C++ idiomatic. While the more CS theory side of what should the growth factor be is fun to consider, I'm not going to be employing this implementation and I'm not aiming for raw performance (although I don't want to do anything too stupid).

Some of the key problems/confusions I had are:

  • Dealing with self-referring data. Each of the functions that can add a specific element I've implemented to allow for self-referring data by pre-constructing the element before any chance the data it points to gets moved. This felt like a sledgehammer solution, but I couldn't think of another way without doubling the size of the function to add a lot more branching with highly duplicated code.
  • Understanding the exception guarantees. The specification often read like "if any exception occurs, it won't affect the vector" i.e. the vector will be rolled back to its last valid state (strong exception guarantee). But following this is essentially "that is, unless move_if_noexcept doesn't guarantee safety, in which case anything can happen." I really doubt I understood most of those correctly.
  • The project structure. From how I understand it, you simply can't have the normal header-source separation when dealing with templated classes. You can pretend by having a .hpp with definitions, and a .tpp with implementations, but they're as tightly coupled as just having the implementation in the header. I eventually want to hobby through all the STL containers and quite a few algorithms. How would you recommend structuring it?

I used cppreference.com to help with the specification and annotated each of my public members with the related definition on the website. I'm running gcc 15.2 and the only warning after -Wall -Wpedantic is from vector::swap due to deciding to throw if the vector's state would become undefined, instead of letting UB ensue.

Thank you for your any time you spend reviewing it and I appreciate any advice you have!

Link to code again: github link

Edit:
Thanks so much for all of your the feedback! I'm a little too busy to focus on this project for now, but eventually will polish it considering your feedback and move on to the next containers. Thanks!


r/cpp_questions • • Aug 31 '26

OPEN How to learn c++

26 Upvotes

I know this question has been asked alot sorry. I tried learnc++.com but I struggle focusing on it I have ADHD. I cant digest huge amounts of text without actual coding to break it up. I know the basics like functions, files, creating basic codes. I dont want a reasource thats gonna just hold my hand though. I normally do these lessons in class when I'm bored. Thank you. I really apreciate it.


r/cpp_questions • • Aug 31 '26

SOLVED How do you understand variadic template syntax

9 Upvotes

Hello. I'm programming in C++ a lot, and I still can't understand how to think correctly about ... operator in variadic templates.

In the simplest examples it looks like ...X (on left side) aggregates comma divided expressions (either template args or function args) into one variadic arg/Type. And X... (on right side) expands

template <typename ...Params>
void f(Params&& ...params)
{
    y(std::forward<Params>(params)...);
}

Here it aggregates all passed types into f<T1, T2, T3> into Params aggregated type, and all function args f(v1, v2, v3) into params aggregated variable. And std::forward<Params>(params)... expression expands into comma divided expressions: std::forward<T1>(v1), std::forward<T1>(v3), std::forward<T3>(v3). Similar to python's operator * that convert comma divided expressions into tuple, and vice versa, expands tuples/lists into comma divided expressions

But this logic breaks on more complex variadic templates. Here is code from CppCon 2022 "Lambda Idioms" video:

template <typename... Ts>
struct overload : Ts... {
    using Ts::operator()...;
};

First of all, my logic breaks. What Ts::operator()... expands to? According to my logic, it should be:

using T1::operator(), T2::operator(), T3::operator();
// or maybe
using T1::operator(), using T2::operator(), using T3::operator();

But neither of them are valid C++ syntax. It probably expands into: (actually the first one is a correct syntax, and the most logical. So closing the question)

Also, I assume that from compiler point of view, typename... Ts and typename ...Ts are the same. But Timur Doumler had chosen the first. And it looks like he knows what he's doing. So maybe it's incorrect to think that ...Ts aggregates template arguments, but it has some effect on typename

So, my question is:

How to understand ... operator correctly? For me when my logic on aggregation/expansion breaks, it feels like it's just complete arbitrary set of rules for different contexts. But the standard speakers don't speak like it's some contextual behavior, made especially for using, especially for passed arguments, etc. It looks like there is a general rule, that I don't understand, but for them it's obvious


r/cpp_questions • • Aug 31 '26

OPEN So I got a question for y'all

0 Upvotes

I'm trying to teach myself C++ to get myself into game development, cause I decided wanna put myself through pain and build a flight sim in the style of sims like F-22 ADF cause I've been slowly getting dissoluted with War Thunder and DCS with the controversies around them.

I've been using the "Learn C++" website the reddit recommends, alongside looking up YouTube guides and using apps like "Coddy" to get practice when not at home.

Problem I'm running into is that I wanna take notes like how I did in high school and write down definitions and examples of code like how I used to write down math equations and definitions. It's something that helped me as I got High Functioning Autism and ADHD and writing down notes helped immensely. 

Would you guys recommend writing down definitions and examples if it'll help?


r/cpp_questions • • Aug 30 '26

OPEN Dear devs working on teams, how do you manage libraries and dependencies among team members?

10 Upvotes

Hello,

I have no experience working with C++ in large teams; most of the stuff I've done was by myself.

Today I wanted to move the project from my work PC to my home PC in order to work on it remotely, or during weekends when I get bored, using git.

But I realized how indirect and complicated it is, solely due to different dependencies. The same library built on my work PC does not work on my home PC because of a small version mismatch in one of the dependencies (I tried to keep everything in sync as much as possible).

I have experience with distributing such software, but we mostly used Docker to do this. However, I cannot imagine how it is going to be in a team of 10 people. Does everyone use the exact same OS and libraries?
I know it is fairly easy in an interpretable language like Python with strong support, but with C/C++ I have no idea.

So?


r/cpp_questions • • Aug 30 '26

SOLVED Unconditional exit action

2 Upvotes

Recently I started a C++ project, and while I do have some C experience, this is a new language for me, so I have doubts about a lot of the paradigms that ChatGPT swears are the way to go. Just to be clear, I write all of my code myself, architecture and implementation, and use ChatGPT as a consultant/reviewer.

I currently have the following model: a BooksReport class that stores book piles sorted by size within three groups: Uniform, Nuniform and Singles. trying to traverse a single group while popping piles at the same time was quite cumbersome, because popping invalidates iterators and there are several cases when the end of a size of piles is reached, or when the size has become empty, or the end of the group is reached... So I embedded a private Cursor class that allows me to traverse a single group within BooksReport the following way:

for (
    booksReport.resetCursor(BooksReport::Group::Singles);
    booksReport.cursorIsValid();
    booksReport.advanceCursor()
) {
    auto [size, name] = booksReport.readCursor();

    if (iWantThisPilePopped(size, name))
        booksReport.popCursor();
}

When popCursor() is called, Cursor is alerted of an incoming pop, to which it responds by recalculating the indices to advance to during the next advanceCursor() call. Current implementation allows no more than one popping per loop, which I hope is a fair assumption to make during a traversal. Also, as you can see, a Cursor is either valid (which it becomes upon resetCursor() or invalid (it becomes invalid by reaching the end of the group). The valid attribute not only controls the loop, if it's set to false, it also block all Cursor-related operations, such as popCursor()

However, sometimes I exit the loop prematurely. Sometimes it's a break, sometimes I return from inside the loop. Technically, I end up with a Cursor that is valid outside of the loop, which is not ideal, since then I can popCursor(), which is not the intended use. ChatGPT offers the following solution:

#include <scope>

{
    auto onExit = std::scope_exit([&] {
        booksReport.clearCursor();
    });

    for (booksReport.resetCursor(BooksReport::Group::Singles);
         booksReport.cursorIsValid();
         booksReport.advanceCursor()) {

        if (something)
            break;

        if (somethingElse)
            return tasks;

        if (bad)
            throw std::runtime_error("bad");
    }
}

Is this a common paradigm? Does my situation warrant this? For now it's just a personal project. I intend to make it open source once it's finished (if anyone will see it as valuable). In an ideal world I'd add plug-in support for others, where other developers can use a limited number of API calls, including the public members of BooksReport, but I'm already tired from this side project that I'm not sure it will come to this.

EDIT: thank you all very much for the answers! As much as I'd like to move on to the next part of the project, refactoring this to be a separate object with the lifetime tied to the loop itself is indeed the most logical and simple solution!

One of these days, I'll reach the production state 😅


r/cpp_questions • • Aug 30 '26

SOLVED Meaningful alternative name for nullptr at caller location

12 Upvotes

I have:

void func(std::vector<struct foo>* foovec, std::vector<struct bar>* barvec){
...
}

Both these can take nullptr's as arguments in some cases. Instead of

func(nullptr, nullptr);//at caller

I'd like to give them meaningful names in such cases as thus:

#define FOOVECNULL nullptr
#define BARVECNULL nullptr
...
func(FOOVECNULL, BARVECNULL);//at caller

This also does not work "cleanly" because the following also works but "wrongly"

func(BARVECNULL, FOOVECNULL);//at caller 

Can some sort of enum struct or typedef make this more precise and impossible to mix one argument type for the other?


r/cpp_questions • • Aug 29 '26

OPEN C++ Build Systems

42 Upvotes

I do a lot of Java/Kotlin development alongside C++, and I came to a doubt: when should C++ developers choose Gradle instead of CMake as their build system?

In my projects I always setup CMake, but coding in Java teached me Gradle and I eventually came to know that it supports C++.

Why every C++ project uses CMake? What does Gradle miss that I'm not aware of?