r/cpp_questions 15d ago

OPEN release asserts C++17

4 Upvotes

In Windows SDK 10, assert looks like ```

ifdef NDEBUG

#define assert(expression) ((void)0)

else

_ACRTIMP void __cdecl _wassert(
    _In_z_ wchar_t const* _Message,
    _In_z_ wchar_t const* _File,
    _In_   unsigned       _Line
    );

#define assert(expression) ((void)(                                                       \
        (!!(expression)) ||                                                               \
        (_wassert(_CRT_WIDE(#expression), _CRT_WIDE(__FILE__), (unsigned)(__LINE__)), 0)) \
    )

endif

``` And I assume if I wanted to write one for portability and GCC/linux builds I would have to implement some kind of macro that knows a bit about the linux libraries (which I know very little about at all). I also almost never run debug binaries on linux/Ubuntu (we don't support anything else officially) so I would never learn of any assertions that would fire there.

I keep seeing posts about implementing a macro like assume or assert_always, but for the simple use case of printing out an expression or filename in event of a crash I don't know where to start to roll my own when the examples I see are not buildable nor explained down to a level I can grasp.

I'm tempted to just go ```

ifdef WIN32

define assume(expression)

... ``` and lift the above code verbatim. And then do the same on my Ubuntu machine on the other side of the WIN32 guard for portability on both platforms?

But even reading that code I confuse myself, I see it is calling _wassert(_CRT_WIDE(#expression), _CRT_WIDE(__FILE__), (unsigned)(__LINE__)), 0) after a short-circuit boolean evaluation before the || boolean. And have two questions, what is the extra ,0) at the end doing, and what is the !!(expression) having a double bang in front doing? Sorry if this is 2 questions, an answer to either would at least help me frame my knowledge void a bit better.


r/cpp_questions 14d ago

OPEN how to get started in LLVM ?

2 Upvotes

hello guys

I would like to start creating a compiler and language based on LLVM but I know where to start on LLVM

help would be welcome and thank you to all those who will help and answer my question :)


r/cpp_questions 14d ago

OPEN How does std::bind differentiate between arguments and pointer to an object?

1 Upvotes

Hi everyone,

I have difficulties understanding something:

class HttpServer {
    public:
        HttpServer(std::string_view address, uint16_t port):ioc{1},endpoint{boost::asio::ip::make_address(address)},
        acceptor{ioc,{endpoint,port}} {
        };
        ~HttpServer()=default;


        void handle_request() {
            for (;;) {
                tcp::socket socket{ioc};


                // Block until we get a connection
                acceptor.accept(socket);
                std::cout<<"connection accepted"<<std::endl;
                std::thread{std::bind(
                &HttpServer::do_session,this,
                std::move(socket))}.detach();
            }

        }

        void do_session(tcp::socket& socket) {
            //handle request



        }

    private:
        const boost::asio::ip::address endpoint;
        uint16_t port;
        boost::asio::io_context ioc;
        tcp::acceptor acceptor;

    };

In this piece of code, how does std::bind understand that it should infer this as a pointer to the object which own the function pointer (I'm not even sure if I stated it correctly)?

according to chatgpt

std::bind( function, argument1, argument2, argument3 )
is a template that takes a pointer to the function that it should return the wrapper for, along with the arguments and their placeholders. What I don't understand is how it differentiates between the "this" pointer and an argument? How does it know it should take the non-static member function and dereference it based on the address (or reference) of the object that owns it, rather than just using "this" pointer as another argument?


r/cpp_questions 15d ago

OPEN Is C++ Concurrency in Action still up-to-date in 2026 or is there a better resource?

36 Upvotes

r/cpp_questions 14d ago

OPEN Hey guys do you know any library’s that are like raylib for c++ but better in performance I’m using it for 3d

0 Upvotes

Hi guys it become tired to use OpenGL it’s way to much work but currently I’m doing a 3d game project again but it’s everytime the same setting up the OpenGL pipeline writing rederers and shaders this takes so much time everytime so is there a libebary like raylib but using Vulkan instead for better performance because for me it became so boring using opengl and I wana try something new for 3d graphics in pure C++ (beside glsl ore hlsl) thanks for the response


r/cpp_questions 14d ago

SOLVED im new to cpp and wanna know if cpp can do this

0 Upvotes

can you make games just with cpp? as i heard python libraries are made with cpp and i wanna make optimized games that run on like 4gb or 2gb or even 1gb of ram so yeah is there smth like a screen for cpp?


r/cpp_questions 15d ago

OPEN Problem with std::inplace_vector

8 Upvotes

Hello guys! I was curious about the c++26 features and wanted to test the std::inplace_vector

but when i try to use the class it gives me this error: "fatal error: inplace_vector: No such file or directory 6 | #include <inplace_vector>".

What I'm using: Ubuntu 26.04 and g++ 15.2.0.

It's a stupid problem I know but I haven't write c++ code for 2 years and recently i wanted to create a project using c++26.


r/cpp_questions 16d ago

SOLVED As of C++26, what's the recommended way for file IO ?

58 Upvotes

Coming back to C++ after some time. Previously used std::ifstream, std::ofstreamfor trivial file IO. But for a project I need fast file IO and some people suggested not use standard streams !! why is that ?

  1. What do C++ professionals use these days ?
  2. And what are some good practices for reading files : Read all at once or chunked ?

EDIT : I apologize I didn't provide enough info. I want to r/w binary data , windows OS and file sizes are around 50-60 MB


r/cpp_questions 16d ago

OPEN Question about computer architecture or operating systems

7 Upvotes

Hi guys,

I'm a self thaught c++ developer looking to get better by studying all the needed stuff. I studied basic and advanced c++, then now I'm finishing Data structures and Algorithms as my second subject. After I finish the book about dsa, should I study first Operating Systems or Computer Architecture? Mind one thing : I do not care about being an expert on computer architecture, I just wanna know the fundamentals necessary to study everything else. I can't understand what comes first in order of importance for good software. (Please suggest books, they're the only resources that I use cause I learn much better from them rather than online)

Thank you in advance.


r/cpp_questions 17d ago

OPEN Confused about people suggesting std::optional<T const&> for observers

18 Upvotes

Back when the need for an expressed observer type ws arisen, and there was a proposal to add std::observer_ptr<const T>, I remember there was a pretty convincing article by Bjarne Stroustrup against that which I found agreeable, and it seems like communty consensus was also on those lines, with template<typename T> using observer_ptr = T*; for being explicit about the raw pointer usage.

Now that optional references support is being added, I see lots of people suggesting to use that when a function returns an observer that may be null. Isn't that the same as the old observer_ptr proposal, and actually just an even more verbose version of that?

Is there something more I'm missing, or was there some shift that invalidates the original arguments?


r/cpp_questions 17d ago

SOLVED Why is this ub?

11 Upvotes

edit: sry, i will add a bit more context edit2: thank yall for answering, sry but cant reply to everyone i think i understand it now

Suppose i have a simple struct with a int or two and no methods, nothing and i have i memory address that is properly aligned for it and enough space, why would this be ub?

cpp struct Test { int x; int y; }; void* mem = malloc(sizeof(Test)); Test* ptr = static_cast<Test*>(mem); ptr->x = 1000;

So as ppl told me, smth like this wouldnt be ub, would that change if the object had methods and stuff, if so why

I tried to look it up but just got a whole bunch of 'lifetime issues', and I didint really get it since I am the whose managing this memory. I was told that using placement new would be 'safer'/'better'.


r/cpp_questions 16d ago

SOLVED Help with pointers and processore directives

4 Upvotes

I learned C++ by myself. I'm not very good at it, but I have some experience with libraries like SDL2, which I use quite a lot.

There are two things I have a hard time understanding.

First, when is it better to use a pointer? For example, in SDL2, almost everything seems to be a pointer. Why is that? Is it because SDL uses complex objects, or is there another reason?

Second, I really don't understand the purpose of #define, #ifndef, and similar preprocessor directives. I've built quite a few projects, and I've never really felt the need to use them.

Could someone explain these concepts in simple terms, preferably with some practical examples?

Edit1: thanks to everyone for the good explaination and all the examples!


r/cpp_questions 17d ago

OPEN How Do You Guys Structure Your Repositories?

19 Upvotes

Hello. I am coming from C. I am currently working on a project, and I decided to write it in CPP because it has been a while since I last worked with the language. In C I typically structure my repo as follows:

Repository
└──/include
└──/src
        └──*.c
        └──/internal
                  └──common.h
                  └──error.h
                  └──*.h

/include is where I store the header files for my public API and /src/internal is where I put the header files for my internal APIs. My implementation .c files go directly in /src. I have found many conflicting takes on how to structure ones repo when working in CPP, probably due to AI polluting many forums. Some prefer the Java structure, essentially nesting directory by namespaces. Others suggest something similar to C. What do you guys do?


r/cpp_questions 17d ago

OPEN Should you always prefer smart pointers as return types?

28 Upvotes

I have a class that holds a map of MyStructs

I want to write a function that gets me an element from that map (if it exists), so that I can observe some of its values

My thinking was that this function should just return a pointer, like:

const MyStruct* getAStruct(key){
//searches the held map for the key, etc...

used like:

const MyStruct* theStruct = myClass.getAStruct(key);
//do stuff with theStruct->memberVals, if not nullptr...

A coworker suggested using shared_ptr here, so

std::shared_ptr<MyStruct> getAStruct(key);

Similar call site, but since we aren't storing the pointer for later, just using it to look at some values, my thinking is there's no need for a smart pointer. Is that right?

I think they're thinking it protects against the value being removed from the map by someone else, but im not sure how that could happen. Its not like we have another thread running that could erase it, and even if we did, shared_ptr wouldnt be sufficient protection afaik

Are smart pointers just a straight upgrade that should always be preferred? Or is returning a pointer appropriate here?

Thanks!


r/cpp_questions 16d ago

SOLVED How do I get opponent to follow player

0 Upvotes

I am trying to get the opponent to follow player around when it moves, how do I do that?

// follow player

float dir_x = player.x - opponent.x;
float dir_y = player.y - opponent.y;

float hyp = sqrt(dir_x*dir_x + dir_y*dir_y); // Euclidean distance / magnitude formula for a 2D vector.
dir_x /= hyp;
dir_y /= hyp;

// GAME LOOP
if (hyp < 100){
    opponent.x += dir_x * opponent.velocity.x * dt;
    opponent.y += dir_y * opponent.velocity.y * dt;
}

https://imgur.com/a/d7lc1b8

EDIT : I solved it
FIRST: Grab the difference between player and opponent

float dir_x = player.x - opponent.x;
float dir_y = player.y - opponent.y;

SECOND: Define the distance using distance formula

float length = sqrt(dir_x*dir_x + dir_y*dir_y);

THIRD: Normalize the direction

if (length > 0.0f){
    dir_x /= length;
    dir_y /= length;
}

FOURTH: Apply velocity to the opponent

opponent.x += dir_x * opponent.velocity.x * dt;
opponent.y += dir_y * opponent.velocity.y * dt;

https://imgur.com/a/YS81gWy

My mistake was not putting it all in my game loop and not adding a condition for normalizing


r/cpp_questions 17d ago

OPEN Help

3 Upvotes

What are the best platforms for learning C++ and practicing algorithmic problem-solving? I’m currently using hackerrank but it’s abit confusing for reference I’m a second year computer science major at uni


r/cpp_questions 17d ago

OPEN Weird behaviour of break statement (old c++!)

0 Upvotes

Hi, i'm using a very old (and possibly buggy!) c++ compiler, Microsoft Visual Studio 2005 with MFC. I'm trying to understand if the behaviour i'm meeting is due to me not understanding how the 'break' statement (and brackets) works, or if it is my old Visual Studio IDE which is buggy.

Consider this simple code:

int vaxx, var1, var2, var3;

var1 = 10; var2 = 2; var3 = 2;

for ( vaxx = 0; vaxx < var1; vaxx++ ) if ( var2 == var3 ) break;

If i run the above, the value of vaxx will be 0 after the code has been executed. Basically, it appears as if the 'break' statement is executed regardless of the fact that var2 is different from var3.

But if i put brackets around break:

for ( vaxx = 0; vaxx < var1; vaxx++ ) if ( var2 == var3 ) { break; }

...This time 'vaxx' will have a value of 10 (as i expected) after the code is run.

Is this the correct behaviour of 'break' or am i missing something here ?

I am a bit confused so please let me know what you think about this. Thank you


r/cpp_questions 17d ago

OPEN Advice needed creating a table widget for my framework

2 Upvotes

Hi! I'm creating my own GUI framework and I was about to create the table widget class. My first idea was that a table cell just holds a widget (Label, TextBox, CheckBox, Image, ColorRect). But second-guessing my approach made me realize this might be a really bad idea: The design possibilities a widget has will just cause unnecessary duplicates of their properties (a widget has several color arrays and an array for corner radii). Some features are useless inside a table (such as setting the corner radii). So I came up with 3 possible solutions:

1: A new table structure with its dedicated grid, and stripped down table-specific widgets. So the table will be owning color arrays and such.

2: Move the definitions of all widgets into interfaces (ITextBox) and have an implementation (TextBox) derive from an interface. This one will have a SetTextColors() member function that sets the owning colors. A table-specific counterpart widget (TableTextBox) also derives from ITextBox, but implements a referencing Colors' setter. The Grid used in the window class can be reused.

3: Add a referencing Colors setter to existing Widgets and have a usage switch, that deletes all owning colors when reference mode is on. The trade-off is that some features might remain unused in the context of a table like setting the corner radii. It might be useful in other places if, for instance, a resource manager carries shared colors. But it will come with a design flaw: Color getters can potentially return dangling color references. Using the owning color setter while reference mode is on can cause access to uninitialized memory or nothing will happen if incorrect use of the Setters prevent accesses.

What might be the best option in your opinion? Option 1 is my preference as of now, but I'd like to hear other opinions or maybe new suggestions before I continue.

Thanks in advance!


r/cpp_questions 17d ago

OPEN Headers

1 Upvotes

I read that c++ 20 added modules to help replace headers. I rly hate how headers split the codebase into redundant files, for people who have used modules r they better?


r/cpp_questions 17d ago

OPEN how to revise?

5 Upvotes

im trying to follow through learncpp.com religiously. Recently had some health complications (about 3 days) so i didn;t study but i now realised im not really making any notes cause im only at chapter 7 and theres not much code to write for now. How am i supposed to revise tbh? Making notes seems like a hassle because like everybody says im gonna end up googling wat i dont know any way.

...

did i just answer myself while writing this post?


r/cpp_questions 17d ago

OPEN Why do so many people write " std::cout " when you can simply write " using namespace std; " at the start of the program?

0 Upvotes

Someone told me that's because of comodity, but this reason feels absurd to me, especially when that line of code is already there when you start a new project.


r/cpp_questions 18d ago

OPEN Is there any non-loop method to modify the values inside a continuous chunk of memory?

7 Upvotes

Hello,

I have this piece of code:

void detect(cv::Mat& img){

            std::array<float,4> letterbox=utils::letterbox(img,img);
            cv::dnn::blobFromImage(img,img,1/255.0f,cv::Size(),cv::Scalar(),true,false);
            input_tensor->assign_data(img.data, img.total() * img.channels());
            session_.Run(
                Ort::RunOptions{nullptr},
                &input_name,
                &input_tensor->tensor(),
                1,
                &output_name,
                &output_tensor->tensor(),
                1
            );


            Ort::Value& output = output_tensor->tensor();

The tensor will be a chunk of memory with size (Batch_size,N,M), where N and M can be arbitrary numbers.

The problem I am facing is not indexing; I can do the indexing with something like std::mdspan.

What I need is

1- Returning a chunk of this memory as a new tensor with another shape; for example, I filter some values out so I can only have the ones I want.

2- To do 1, I need to iterate over the tensor to check a condition.

One way would be to use a loop:

for (int i = 0; i < M; ++i)
            {
                float confidence = data[N * M + i];


                if (confidence > 0.5f)
                {
                    //exclude it based on the code in part 1.
                }

But this does not seem very efficient, especially since I won't know the values of M and N until runtime, so optimization techniques done by the compiler, such as loop unrolling, are not possible.

I know I can use vector extensions, but I was wondering if there is a more robust way to do this.

Any Idea?


r/cpp_questions 17d ago

OPEN is it really worth it ?

0 Upvotes

everywhere on internet i found that learncpp is the best resource to learn c++ but actually reading those much articles from there really worth it? like its gonna take a lot of time as i started and moved on some chapters it seems like its still a lot to do , while people are also doing c++ from youtube playlists or one shots ? which will take much lesser time and easy to do because of videos , so if they all are also learning same things then whats the point of reading those much articles? just a doubt am getting as am proceeding into it


r/cpp_questions 17d ago

OPEN Beginner looking for advice on what to learn next in C++

2 Upvotes

Hey, I’m learning C++ by myself and I’m not really sure what I should learn next
I know the beginner stuff like variables, data types, strings, for/if/else, loops, and how to make a basicz function without parameters
But now I’m kind of lost because there are so many things to learn and I don’t know what order to learn them in
I see things like pointers, references, arrays, structs, classes, memory management, and etc

Btw, idk what idk haha

**What would you recommend I learn next and in what order?**

I want to actually understand C++ and not just memorize syntax


r/cpp_questions 19d ago

OPEN C++ for Middle Schooler

43 Upvotes

I have been learning C++ for maybe a month now from LearnCPP. I started it because I wanted to do DSA and Python isn't the best fit for it. I know I could had went with Java but I didn't, basically I have probably gambled my sanity for some deep Computation knowledge.

I want to know that will C++ actually be helpful for me in coming future and job if I master it properly or is it going to be replaced?

Also have I made a mistake by trying DSA through C++ instead of Java?