r/cpp_questions

Complexity of a simple function.

Inspired by a recent posting here that was deleted (it was apparently homework) I cooked up the following simple function.

I was a little bit surprised by the result, not its general direction but how clean it was.

It should be easy to verify that I'm not a student, e.g. in its day I was a co-moderator of Usenet group comp.lang.c++.moderated. I just wonder if there is a simple, clean explanation, not heavy math-ish analysis? Explanation for not seeing the obvious: it's early morning, I still need my coffee.

auto foo( const int n ) -> int
{
    int sum = 1;
    for( int i = n - 1; i > 0; --i ) {
        sum += foo( i );
    }
    return sum;
}

#include <print>
using std::print;
auto main() -> int { print( "{}.\n", foo( 9 ) ); }
reddit.com
u/alfps — 3 hours ago

Quadratic behavior with nested generators?

Consider the type definition

struct list {
  list* next;
  int value;
};

I have heard the claim that this code:

generator<int> list_values(list& l) {
  co_yield l.value;
  if (l.next) {
    co_yield elements_of(list_values(*l.next));
  }
}

Has linear runtime, whereas this one:

generator<int> list_values(list& l) {
  co_yield l.value;
  if (l.next) {
    for (int x : list_values(*l.next)) {
      co_yield x;
    }
  }
}

Has quadratic runtime due to successive suspension/resumption of nested coroutines.

Is this true? Also I haven't actually found a good source for this claim except for a blog titled "C++ Coroutines Don't Spark Joy" but I am hoping there is something better out there

reddit.com
u/sebamestre — 5 hours ago

Speed of std::shared_mutex on MinGW unusually slow compared to MSVC and Clang under wsl.

Hello, I have a project which I did some profiling for recently, and noticed an unusual pattern: the cost of std::shared_mutex and specifically shared lock / unlock was unusually high (made entire runtime at least 5x slower) when compared to running the same code compiled with MSVC and clang under WSL. Any ideas on why this happens?
(the hyperlink points to the specific commit that I did profiling in.)

In recent commits I have done some work to require a lot less shared locks / unlocks, which has helped my total run time a lot, but some assistance in why this is happen and if there any solutions for it would be useful.

My use of std::shared_mutex is as follows: I have a global data state (see GState / g_ecs_data) which has some 'initialized on demand fields'. Anything that accesses these on demand fields is guarded by a std::shared_lock and anything that writes is guarded by a std::unique_lock.

( you can find the specific mutex in my repo with the keyword "archetypes_mtx" on the main branch (archetype_mtx on develop branch). while develop is where I do most of my work, main has all the necessary code for discussion)

for some actual numbers:
MinGW. 10-11 seconds for all threads to finish
MSVC: 700-800 ms for all threads to finish
Clang WSL: 900-100 ms for all threads to finish

reddit.com
u/LivingTheDagor — 6 hours ago

Hyper-Threading and C++ parallel computing

if my cpu has hyperthreading (HT)capability(one physical gives two logical threads), when planning for memory locality should i simply divide the thread private memory capacity(L1 cache, and registers) by two? are there further implications? or should i simply run my cpp parallel program with no two threads coming from a same core( is there a way to run the program switching off HT or should i switch off HT in bios when booting my computer)

to consider a concrete example, if i do parallelized tiled matrix multiplication, and i intend to fit my matrix tiles into registers private to a core, how to do that when my cpu has HT? should i simply divide the capacity of registers private to a core by two?

reddit.com
u/OkEmu7082 — 6 hours ago

Making Coroutines More Deterministic in Embedded

Hey!

By overriding the operator new in the promise_type in coroutines you can apparently use your own allocator - there is a pigweed blog on this somewhere. However, if you wanted to use coroutines in embedded with async runtime kinda like embassy in rust instead of an RTOS I want to understand how you “tame” the heap allocation to make it more deterministic.

I am not super familiar with this area….apparently there is no way to get the coroutines size at compile time. In embedded you might wanna make your own pool allocator. For this and not to waste memory it would be good to know the size of the coroutines frames exactly if they are allocator allocated.

So do you introduce a build script for your projects that compiles and records the sizes of the coroutines when they call new with a logger compiled in? Without guessing is this literally the professional way to get some level of certainty? It feels kinda crude :(

There was an open std pdf on getting some decent compile time failure if they exceed a size but as far as I can tell it was never implemented (maybe I am being dumb?) P1365r0.pdf

reddit.com
u/wandering_platypator — 21 hours ago

What book is good to start? I've been read C++ prime but then I note that it's better to use it as a dictionary and does't like a tutorial or introduction

I think use this book of pirme like a deep manual, however I need a book which guide me.

reddit.com
u/AttentionCandid3912 — 24 hours ago

Any tips on how to make lower level code more testable

I have been learn cpp for some months and started doing a project of making a chat server with a custom event loop using epoll for learning purposes.

But current i am not really sure on how to make these lower level code like interacting with os more testable and also on how to test it. I would like to have some tips/resources on this.

The trial and error method has been a bit frustrating 😅

Also ways to check and reduce unnecessary allocation would also be nice.

reddit.com
u/Cold-Armadillo-154 — 1 day ago

Need some suggestions for a personal project

I'm not a beginner and I have done a couple C++ projects. I have done a ray tracer using Ray Tracing in One Weekend series. I have done a very simple Unix Shell and a simple matching engine with a limit order book(nothing too crazy). And I have also dabbled with some collision physics + OpenGL. Any good project ideas for an intermediate like me?

reddit.com
u/Zealousideal_Comb694 — 2 days ago

I want to learn C++, but I am failing for months

I want to learn about C++ the whole thing, but I tried a few times, but even after that I couldn’t I have ADHD . I know a few basics, but no nothing else after that. Can you guys suggest me what I can do to learn cpp .

Can you guys suggest me what pathway helped you the most? Or what kind of things I should do

reddit.com
u/Upset-Fee-9118 — 3 days ago

Status of C++ Concurrency today and what paradigms are used in real world codebases?

Background - We learnt OpenMP, MPI and Cuda in uni, where major focus was on throughput/HPC, so this might already be irrelevant at least for CPU side of things.

But to learn and to write latency sensitive multi threaded applications,

I was going through C++ concurrency in action book, read till chapter-4 which introduced std::async, std::packaged_task, std::promise bundled with std::future and various paradigms for approaching concurrency like pure functions(Functional programming) and Actor model wherein each thread is a state machine, and communicates with other thread via message passing mechanisms, which resonated a lot with MPI. I don't even know if they are used in modern C++.

Book also introduced experimental features, continuation in particular, of future, shared_future, when_any, when_all, which are unfortunately/fortunately still in experimental, from what I can see in cppreference, and I learnt that std::execution largely replaced them to model task dependencies.

And there is something called coroutines too for non-blocking executions, which I know nothing about. So, in conclusion, there are many ways to approach concurrency, and I am still in chapter-4 of this book. This is messing up my head. Might be because I never wrote any multi threaded application, its all in theory.

Coming to question in title, I know there is no single paradigm/design to approach writing multi threaded applications, but any direction/guidance/resources could help me use things that modern C++ recommends.

reddit.com
u/unordered_memory — 3 days ago

Is it optimal to create classes that inherit from std classes?

I have a small program that I've re-written from C that contains functions that accept either DIR* or FILE* to represent directory and file objects.

Now I want to use std::filesystem, but std::filesystem only contains the class directory_entry, which can either be a regular file, block file, directory..etc

I mean yeah sure, I can do checks before feeding them to functions and such stuff, but I want to make it clear and readable that this function explicitly accepts this file type.

I thought about maybe aliasing names, but still that doesn't affect the functionality, so I thought about creating classes that inherit from the std::filesystem::directory_entry class.

What do you think? and is there a better thing to do?

Thanks in advance.

reddit.com
u/Ultimate_Sigma_Boy67 — 3 days ago

Evaluate enum class in a boolean context (type-safe enum flags)

I've been toying around with type safe flags from enums, but instead of a separate class flag_set<T>, I've tried to

  • overload required operators (like &, | etc.)
  • a method to "tag" enum types to make the feature opt-in

(godbolt example here)

The core idea is not to introduce a separate type, but to use "standard" syntax but make it type safe (e.g., fail when mixing distinct flag sets).

I think I have everything covered except one very common thing:

enum class EFlags { Read = 1, Write = 2, Sleep = 4 };

void enable_bitset_enum(EFlags); // opt-in

EFlags a = ....;

if (!(a & EFlags::Read)) { }  // ok
if (a & EFlags::Read) { }     // doesn't compile

This boils down to evaluating EFlags in a boolean context, which... I have no idea how to enable.

(It's making me unecessarily angry because everything else works, just nto that)

Any ideas?

u/elperroborrachotoo — 3 days ago
▲ 3 r/cpp_questions+1 crossposts

Zero copy CUDA GPU presentation of AvFrame.

This is quite specific and not exactly c++ specific but I've been searching for days and can't find anything. I'm trying to implement displaying an AvFrame from ffmpeg that has been hardware decoded into the CUDA_FORMAT on an egl surface. I've already implemented the same thing using vaapi for Intel and amd but I can't find any examples of anything for Nvidia. Any help pointing me in the right direction would be greatly appreciated. Important constraint is I do not want to copy the pixels into CPU and then upload back into the gpu, when they are decodes in the GPU, it is imperative they stay there and are read directly as an egl image.

reddit.com
u/Rigamortus2005 — 3 days ago

Learning C++ and feeling kinda lost, what should I do?

Hi, I´m 15, learning C++ with LearnCPP. I´m currently on chapter 14, where is introduction into OOP, classes...

For the theoretical part, I think I understand everything up to this point pretty good, but when it comes to real programming, I´m a little lost. I think the problem is that I don´t have enough of the practical experience, to fully understand it. I tried using AI to give me some exercises, and projects I can build, but none of that really makes difference, cause it is all theme specific and I just can´t figure out, how to use the code in real applications.

Do you have any ideas how can I get better not at understanding the theory, but really building something?

All the people are saying, "Just build something, you learn by experience", but that isn´t the problem, the problem is what to build.

Do anyone have any ideas?

reddit.com
u/DraftOk1709 — 4 days ago

Finally got a modern laptop, what is a good IDE?

So I have an 18 year old laptop that I finally replaced with something new.

I had been using Visual Studio 2011, the newer one wouldn't even run on my old laptop last time I tried.

But now I need to get an IDE again because I lack the original install files for VS 2011, and so I figure on taking this opportunity to ask around about the different options. The new VS being so heavy that it can run on hardware that runs VS 2011 just fine seems like a big mark against it in my mind.

That said, here are the details of my situation, I have split the drive into extra partitions, expecting to put android x86 on one partition and another for experimenting around with linux or other OS options.

I would rather avoid a command line compiler. I am confident I can handle command line tools, but I much prefer gui.

I work on small projects for myself to learn and grow my skills and capabilities. I have no school not work needs for this, but that also means I generally just stick to default settings.

I do want to try out experimenting with the NPU, which I have already figured out is not standardized yet so I am already working on getting documentation for my hardware.

Advice, options, and suggestions are welcome.

reddit.com
u/darklighthitomi — 4 days ago

which is closer to rust trait? CRTP or template + concept or something else

the stateless ABC interface is similar to rust trait in the sense that it allows default behavior in base class by non pure virtual functions, but it is run time polymorphism only. the template + concept does not seem to allow default behavior in "base type"

in modern cpp, how to use boiler plates to get as close as possible to Rust's traits, which is like a stateless ABC interface but is compile time polymorphism?

reddit.com
u/OkEmu7082 — 3 days ago

Seeking feedback on my new library SoaTable

I've been working on SoaTable, a header-only C++23 library that stores data as a Structure-of-Arrays (one contiguous array per field) but keeps a row-shaped API on top: you insert() a record, assign<Column>() fields to it, and iterate with view<Position, Velocity>().

The goal was to get columnar/cache-friendly layout without

forcing the code that uses it to think in columns.

Repo: https://github.com/bbalouki/soatable

A few design points that might be worth discussing here:

1- Columns are sparse and optional per row. A record only pays for the fields it actually has. Data-less column types (struct Frozen {};) act as tags and cost \~nothing. Reading a missing field is a defined "not present", not UB.

2- Handles are generational. insert() returns a row\_id that survives erase, insert, and full re-sorts, and a stale handle reports itself invalid instead of aliasing a reused slot (ABA).

3- Joins start from the smallest column. view/select<A, B>() scans the smaller of the two validity sets and probes the other, so selective queries touch far fewer rows.

4- Layout is a policy, not a rewrite. soa\_table (flat, 64B-aligned), aosoa\_table<Tile> (tiled, growth never copies), pmr\_soa\_table (arena/pool), and mmap\_soa\_table (larger-than-RAM) all share the identical row API.

5- Zero-copy escape hatch. column<T>() hands back a std::span over the real aligned storage for SIMD/BLAS/FFT, with a separate validity bitmap.

6- Opt-in everything. Core is one dependency-free header; compute, query/group-by, serialize, concurrent, timeseries, units, and a runtime dynamic\_table are separate headers you include only if you use them. There's also a SOATABLE\_NO\_EXCEPTIONS / no-RTTI build for embedded/flight targets, kept honest by a dedicated CI leg.

Where it earns its keep: large, sparse tables with selective queries (ECS worlds, tick stores, telemetry).

Where it doesn't: if the table is small, every row has every field, and every pass touches every field, a plain std::vector<Struct> is simpler and just as fast. I tried to be upfront about that in the README.

Numbers (selective join, 250k rows, Release; machine-dependent, harness in the repo):

smallest-drawer select \~168µs vs \~1.55ms when forced to start from the largest column, vs \~1.06ms for a hand-rolled columnar scan and \~1.30ms for an AoS branch scan.

It is not an ECS framework (no systems scheduler, no archetypes), it's the storage layer, so it's more comparable to a sparse-set column store than to EnTT/flecs.

C++23 required (GCC 13+, Clang 18+, MSVC VS2022), CMake/Conan/vcpkg.

Feedback on the API, the sparse-column design, and the benchmark methodology is very welcome m, especially from people doing ECS or columnar-analytics work.

reddit.com
u/bbalouki — 3 days ago

clang is warning me about not handing errors

I used fopen() top open the file:

bool LogListenerThread::readline(FILE* file, std::string&amp; line) {
    char ch(0);
    size_t nbytes(0);
    line = "";
    do {
        nbytes = fread(&amp;ch, 1, 1, file);
        if ((ch == 0x0d) || (ch == 0x0a)) {
            return true;
        }
        line += ch;
    } while (nbytes);
    return false;
}

And clang is giving me a warning here that I'm not understanding, it says: "File position of the stream might be 'indeterminate' after a failed operation. Can cause undefined behavior [clang-analyzer-unix.Stream]" I'm checking that no bytes return and bailing if I hit EOF. What is wrong with this fread() call in the code?

reddit.com
u/zaphodikus — 4 days ago