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 — 6 hours ago

C or C++ to learn OS/low level

Hey everyone,

So I am interested in learning about OS from a book called "Operating Systems: Three Easy Pieces", however it requires C. I want to main C++, but I've heard that the correct way to use modern C++ is to not worry about the manual memory management stuff (that C does) and use the std features. However, I want to learn those nitty gritty low level stuff before moving on to the features that abstract away from them. Would it be better to learn the low level stuff now or keep going with C++ and learn under the hood later?

reddit.com
u/Ryuzako_Yagami01 — 2 hours ago

What's your practice on using noncopyable mixins vs. explicit memer deletion?

I can make a a class Foo move-only by

class Foo
{
public:
  Foo(const Foo &) = delete;
  Foo & operator=(const Foo &) = delete;
};

that's not too bad and almost idiomatic, but the class name is repeated 5 times, and there are minor details (& vs. const &) to get wrong in a hurry.

(yes, technically, the operator= return type doesn't matter and could be void, but that's likely to trip up readers, reviewers and style checks)

Even before move semantics and explicitely deleted special functions, there were noncopyable mixins like boost::noncopyable to make the intent explicit and brief.

What's your take on this? Do you regularly mark classes as non-copyable explicitely, and which way to you prefer?

reddit.com
u/elperroborrachotoo — 2 hours ago

Tools for debugging uwp executables?

Is there any way to debug proprietary windows app executables? I can access executables in C:\Program Files\WindowsApps but for some reason I cannot use gdb. Is there other debuggers?

reddit.com
u/adminstrator123 — 3 hours ago

Why does assigning a function to a struct bloat my binary size?

For some reason when I assign a function to a struct, my compiled binary size jumps up 0.5kb. I know it is the struct causing this because I can use the function in other parts of my code without it jumping up.

The reason I am storing it in a struct anyways is because I need to iterate over some data & find the relevant function to act on that data. Checking every possibility & calling the specific function name from there doesn't sound fun.

I wouldn't mind the 0.5k if it was just that, but I have a ton of little modules each with their own struct instance holding their own separate function & it stacks up quick.

Here is one of my modules so I can show an example of what EXACTLY I am doing that is causing this behavior:

\#pragma once



\#include "../Common.hpp"

\#include "../ScopeState.hpp"





void INST\_End\_exec(const Instruction& inst, const InstToken& token, ScopeState& state, const std::vector<std::string>& args, const std::string& symbol) {

	return;

}





Instruction INST\_End {

	0,

	0,

	//INST\_End\_exec,

};

Un-commenting the `//INST_End_exec` line bumps the size, & I'm pretty sure it's not that the compiler was just passing over the function before, because I use it in other parts of my code-base.

I would be really grateful if someone told me why this is the case & if theres an alternative way I can store my functions...

reddit.com
u/PhosXD — 5 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 — 8 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 — 9 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 — 9 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

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 — 1 day 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 — 2 days 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 — 4 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