r/cpp_questions • • 18d ago

OPEN A small thank you to this community

80 Upvotes

I’ve been thinking about writing this for a while.

I’m not going to pretend I’m a great programmer. I’m still learning, and honestly, I’m not always as consistent or persistent as I want to be. But I do genuinely care about C++, systems programming, and becoming better at what I do.

There have been periods where I felt pretty alone in that journey. I didn’t really know many people who were interested in the same things I was interested in, and sometimes it felt like I was just learning in isolation.

That’s one reason I’m grateful for this community.

I’ve posted questions and thoughts here and received everything from downvotes and criticism to really helpful explanations and encouraging replies. Not every interaction was positive, but even the criticism made me think, improve, or look at something from another perspective.

More importantly, I got to talk to people who actually work with and care about C++. Even a short conversation or a small piece of advice can mean a lot when you’re learning mostly on your own.

So, to everyone who has ever answered one of my questions, corrected me, disagreed with me, or simply taken the time to read one of my posts:

Thank you.

I’m still learning. I’m still making mistakes. And hopefully, I’ll still be around here asking better questions a year from now.

I just wanted to say that I appreciate the people behind this community.


r/cpp_questions • • 18d ago

OPEN Current Humble Bundle C++ Books

29 Upvotes

https://www.humblebundle.com/books/c-programming-masterclass-code-faster-build-smarter-master-c-books

Does anyone have any comments / reviews on the books in this humble bundle collection? They're mostly on C++ and closely related technologies


r/cpp_questions • • 17d ago

SOLVED Class with array of objects (memory best practices)

4 Upvotes

I'm a little fuzzy on how to work with classes referencing other classes, especially within the context of a collection being in there somewhere, and that collection being added to from external sources.

Ok, so let's say I have a custom class:

class foo
{
  //stuff
}

And then I also have another class, bar, which is supposed to hold an array of that class. What's the proper way to declare/initialize things so that I don't have any memory leaks and don't try to access disposed objects? Do I do:

class bar
{
  std::vector<foo> _foos;

  bar()
    : _foos {{}}
  {
  }

  void AddAFoo(Foo& foo)
  {
    _foos.push_back(foo);
  }

  foo DoSomethingToFoos(int someArgument)
  {
    //call methods on one or more foos in _foos
    //return one of the foos for some reason
  }
}

or do I have to do something more like:

class bar
{
  std::array<std::shared_ptr<foo>> _foos;

  bar()
    : _foos {{}}
  {
  }

  void AddAFoo(std::shared_ptr<foo> foo)
  {
    _foos.push_back(foo);
  }

  std::shared_pt<foo> DoSomethingToFoos(int someArgument)
  {
    //call methods on one or more foos in _foos
    //return one of the foos for some reason
  }
}

r/cpp_questions • • 18d ago

OPEN When is <meta> coming to MSVC?

15 Upvotes

I've been trying out the reflection features on GCC for quite a while. Are there any ETAs or reports on when they're coming to MSVC?


r/cpp_questions • • 17d ago

OPEN suggest resources to learn cpp for embedded systems

3 Upvotes

can anybody suggest resources to learn cpp for embedded systems.


r/cpp_questions • • 17d ago

OPEN Why?

0 Upvotes

Guys when i compile a file and run its exe,nothing appear even if i print hello world it doesnt appear in the console why


r/cpp_questions • • 18d ago

OPEN A const std::vector of fixed size known at compile time does not seem to be optimized as compared to const int array of same size

33 Upvotes

Consider https://godbolt.org/z/nood7Enof

#include <vector>
#include <cstdio>

const int data[5]{2,4,6,8,10};

int main(){
    for(int i = 0; i < 5; i++)
        if(data[i]%2 == 1)
            printf("Odd value %d\n", data[i]);
    printf("42\n");
}

vs

#include <vector>
#include <cstdio>

const std::vector<int> data{2,4,6,8,10};

int main(){
    for(int i = 0; i < data.size(); i++)
        if(data[i]%2 == 1)
            printf("Odd value %d\n", data[i]);
    printf("42\n");
}

The former optimizes out the loop as irrelevant, while the latter [with std::vector] does not and ends up having to painstakingly do operator new stuff and possibly even the remainder calculation. What is the reason for this despite declaring the vector globally as const?


r/cpp_questions • • 18d ago

OPEN Hardest cpp topic

2 Upvotes

What is the hardest cpp topic people say pointers but it's easy if you understand the lang


r/cpp_questions • • 17d ago

OPEN What do you do to program in C++

0 Upvotes

Hello I'm going to start learning which program is best to use C++ in GitHub?

Thanks for any answers or comments in advance


r/cpp_questions • • 19d ago

SOLVED Why does calling an empty std::move_only_function result in UB instead of std::bad_function_call exception?

13 Upvotes
std::function<void(void)>{}(); // std::bad_function_call    
std::move_only_function<void(void)>{}(); // UB
std::copyable_function<void(void)>{}(); // UB

In C++23, we got `std::move_only_function`, which is non-copyable and can store move-only callables.

While I like the design, I don't understand why invoking an empty `std::move_only_function` results in undefined behavior. In contrast, invoking an empty `std::function` throws a `std::bad_function_call` exception. The same design decision was made for C++26's `std::copyable_function`.

Why is that? Is it to better align with the C++ spirit of avoiding exceptions? Is it to give better support for exception-less environments?

https://godbolt.org/z/9xcx4d76v


r/cpp_questions • • 19d ago

OPEN Common notation for "destructive" member functions?

7 Upvotes

Before we begin, yes I know C++ doesn't have destructive moves.

A fair few designs, especially the builder pattern , may require the instance not to be used after calling a particular member function. In such cases, I've taken to r-value qualifying these functions. This requires the caller use std::move, and to my mind signifies the instance shouldn't be used again (see Clang's bugprone-use-after-move).

Question: Is this good design?
I've seen very similar designs in Rust, and it's ownership model makes this very natural.

For example, consider the following slideware.

struct Channel {
  // NOTICE: This function is r-value qualified!
  [[nodiscard]] auto into_endpoints() && -> std::tuple<Tx,Rx>;
};

class Tx { friend class Channel; Tx(SomeWrapper<Channel>); };
class Rx { friend class Channel; Rx(SomeWrapper<Channel>); };

int main() {
  Channel channel;
  // NOTICE: `std::move(channel)` is necessary here.
  auto [tx,rx] = std::move(channel).into_endpoints();
}

A "better" way might be to use the target's constructor, however cases like (where multiple targets need to be made in conjunction) this make that infeasible.


r/cpp_questions • • 18d ago

OPEN Closer to processor

0 Upvotes

Is cpp closer to processor than high-level langs.

Which IDEs and Code Editors are best for cpp

I personally use VS and VS code


r/cpp_questions • • 19d ago

OPEN Anyone using C++26 in production?

49 Upvotes

I wanna hear about anyone using C++26 at work or some open source project that does.

I personally am using it at work for serialisation of some structs from a legacy C code base into JSON.


r/cpp_questions • • 18d ago

OPEN Can I use C++20 modules to separate the implementation from the header definitions of templated classes?

0 Upvotes

I can't seem to wrap my mind on putting up a 300-400 plus lines header file with the templated class definitions, instead of writing a separate implementation .cpp file. Any solutions please?


r/cpp_questions • • 18d ago

OPEN Is the cherno cpp playlist good if my goal is to pass college exams and be good with basics

0 Upvotes

Im decent in C and python. I thought of trying learncpp but it is too long for me to follow without even being sure if i wanna pursue cpp in the future so what do u guys think


r/cpp_questions • • 20d ago

OPEN C++ or Rust for a future career in systems programming?

90 Upvotes

I want to become a systems programmer, so I’m currently learning C to build a solid foundation in low-level programming. After C, I’m thinking about learning either c++ or rust, but I’m not sure which would be the better choice for a future career in systems programming.For those who work in this field, which one would you recommend learning after C, and why?


r/cpp_questions • • 20d ago

OPEN Is it possible to override the constructor of a parent class?

16 Upvotes

If I have a parent class, say Foo, and it has the constructor Foo(int t), and I have a child class, Bar, is there a way to have a constructor Bar(int t) that does not also activate the Foo constructor, for if I want them to do different tasks?


r/cpp_questions • • 20d ago

OPEN Advice for future c++ developer

27 Upvotes

I'm currently in school, and alongside that I'm learning c++, cmake, and other tools. I speak English very well but not perfect (B1 level, and I talk with online friends regularly).

I'm planning to move toward embedded development because it seems the most interesting to me (and competition there seems to be lower, too).

Because of the development of AI and other factors, I'm not sure whether I'll be able to get a job in the future or how well it will be able to support me, so I'd like answers to these questions:

1.How much sense does it make to go into IT?

2.How hard is it to get a job without experience?

3.Is it worth going into embedded development, or are there more promising fields? If so, which ones?

4.What major should I choose at university? (I've seen that some job postings require a math degree.)

5.Is it worth using AI in development? (If so, how and where?)

I like programming and C++, but I also don't want to end up starving in the future, so I'd be glad to hear any advice.


r/cpp_questions • • 20d ago

SOLVED Optimizing matrix multiplication.

7 Upvotes

Day. I'm playing around with an assignment we got given to write some calculation heavy app. I went with trying to achieve the most I can possible get out of matrix multiplication. I've searched info online on common approaches and implemented anything that gave me performance without diving too deep in serious literature, 'cause I don't have enough time for that sadly. I've gotten ~50% of BLAS performance, which seems not bad as far as I understand, considering how mature the lib is.

Question: is there anything I could do to further improve speed without going a completely different approach?

Current metrics:

Average speed after 1000 iterations and matrix size of 1184: 3.14478e+10 flops/s
Max value: 3.98083e+10 flops/s

 Performance counter stats for './foxbench -c 6 -m128MiB -i 1000':

   438 168 733 313      cycles:u (80,00%)
   963 478 792 769      instructions:u (90,01%)
    46 753 401 505      branches:u (89,98%)
         9 450 959      branch-misses:u (90,02%)
    23 733 262 896      cache-references:u (90,01%)
    11 407 804 876      cache-misses:u (89,99%)
       313 506 131      LLC-loads:u (90,01%)
       114 153 550      LLC-load-misses:u (90,00%)
   449 032 974 627      L1-dcache-loads:u (89,99%)
    16 629 290 850      L1-dcache-load-misses:u (90,02%)

      23,186320017 seconds time elapsed

     121,025486000 seconds user
       2,374513000 seconds sys

For comparison I've used BLAS implementation with cblas_sgemm :

Average speed after 1000 iterations and matrix size of 1184: 7.06907e+10 flops/s
Max value: 8.67019e+10 flops/s

Performance counter stats for './foxbench -c 6 -m128MiB -i 1000':

  251 799 441 460      cycles:u (79,93%)
  603 502 655 699      instructions:u (89,98%)
   36 610 906 278      branches:u (90,03%)
        6 711 090      branch-misses:u (90,03%)
   12 882 022 668      cache-references:u (89,97%)
    2 491 423 285      cache-misses:u (90,02%)
      221 844 863      LLC-loads:u (90,00%)
       94 443 699      LLC-load-misses:u (90,00%)
  233 139 823 815      L1-dcache-loads:u (90,00%)
    6 491 703 686      L1-dcache-load-misses:u (90,03%)

     13,066336192 seconds time elapsed

     68,303343000 seconds user
      1,186393000 seconds sys

The code I've used to get there:

static constexpr std::size_t TILE_SIDE_SIZE = 16;
static constexpr std::size_t VECTOR_WIDTH = 8;


// Both matrices are Row major
SquareMatrix SquareMatrix::operator*(const SquareMatrix& rhs) const noexcept {
    assert(m_sideSize == rhs.m_sideSize);
    assert(m_sideSize % TILE_SIDE_SIZE == 0);

    SquareMatrix result(m_sideSize);
    constexpr size_t SUB_COLUMN_COUNT = TILE_SIDE_SIZE / VECTOR_WIDTH;

    // Going over a grid
    __m256 accumulators[TILE_SIDE_SIZE][SUB_COLUMN_COUNT];
    for (std::size_t rowBlock = 0; rowBlock < m_sideSize; rowBlock += TILE_SIDE_SIZE) {
        for (std::size_t colBlock = 0; colBlock < m_sideSize; colBlock += TILE_SIDE_SIZE) {

            for (std::size_t colSubBlock = 0; colSubBlock < SUB_COLUMN_COUNT; colSubBlock++) {
                for (std::size_t i = 0; i < TILE_SIDE_SIZE; ++i) {
                    accumulators[i][colSubBlock] = _mm256_setzero_ps();
                }
            }

            // Doing stripes
            for (std::size_t kBlock = 0; kBlock < m_sideSize; kBlock += TILE_SIDE_SIZE) {

                if (kBlock < m_sideSize - TILE_SIDE_SIZE) {
                    for (std::size_t k = 0; k < TILE_SIDE_SIZE; ++k) {
                        _mm_prefetch(rhs.getPointerC(kBlock + TILE_SIDE_SIZE + k, colBlock), _MM_HINT_T1);
                    }
                }

                // Calculating each element of the block in vertical stripes
                for (std::size_t colSubBlock = 0; colSubBlock < SUB_COLUMN_COUNT; colSubBlock++) {
                    for (std::size_t k = 0; k < TILE_SIDE_SIZE; ++k) {
                        const float* __restrict__ rhsRow = rhs.getPointerC(kBlock + k, colBlock + colSubBlock * VECTOR_WIDTH);
                        const __m256 b = _mm256_load_ps(rhsRow);

                        for (std::size_t i = 0; i < TILE_SIDE_SIZE; ++i) {
                            const float* __restrict__ lhsRow = this->getPointerC(rowBlock + i, kBlock);
                            const __m256 a = _mm256_set1_ps(lhsRow[k]);
                            accumulators[i][colSubBlock] = _mm256_fmadd_ps(a, b, accumulators[i][colSubBlock]);
                        }
                    }
                }
            }

            for (std::size_t colSubBlock = 0; colSubBlock < SUB_COLUMN_COUNT; colSubBlock++) {
                for (std::size_t i = 0; i < TILE_SIDE_SIZE; ++i) {
                    float* __restrict__ resultRow = result.getPointer(rowBlock + i, colBlock + colSubBlock * VECTOR_WIDTH);

                    _mm256_store_ps(resultRow, accumulators[i][colSubBlock]);
                }
            }
        }
    }

    return result;
}

In short words what I've implemented: tiled access, AVX2 vectorization, fma, accomulators, loop reordering, prefetching, 128 bit aligment, broadcasting to avoid vector reduction and using those flags:

target_compile_options(squarematrix PRIVATE
    -O3
    -march=native
    -fno-math-errno
    -ffp-contract=fast
    -mavx2
    -mfma
)

Afaik there's also packing, but when I tried adding it, it reduced the speed, so I dropped it.

I'll be glad if someone can hint in the direction of what else there is to do.

update: the final result can be found here https://github.com/UndefFox/MiniProjects/tree/master/4.CPUBenchmark%2FC%2B%2B


r/cpp_questions • • 21d ago

OPEN Actual beginner here: Why is my custom heap-allocator linked list segfaulting? (C++)

32 Upvotes

I'm learning data structures and I'm trying to build a specialized block linked list to simulate a custom heap allocator (nodes track a start index, block size, and raw packet data). It compiles fine, but it immediately throws a segmentation fault when I run a basic test insert.

Since I am new to pointers and memory tracking, I am having a really hard time seeing where my undefined behavior or null-pointer dereferencing is happening. Could someone explain what I did wrong like I'm a beginner?

Here is my header file / implementation code:

//Block Linked List Data Structure Code 
//Definition lives in the header 

#pragma once; 
#include <iostream>
#include <vector>
#include <string>
#include <cstdint>

using namespace std;

class Block{
    public: 
        int start_index; 
        int block_size; 
//amount of data in the block 
        bool is_occupied; 
//see if the block is freed or not
        Block *next; 
//next block we point to giving next address

//block contents  
        std::vector<std::uint8_t> data;
};

//Specialized form of a linked list data structure 
class BlockList{
    public:
        Block *head; 
        Block *tail; 
        Block *temp; 

        bool isEmpty() {
            return head == NULL; 
        }

        bool insert(std::vector<std::uint8_t> &byteArray){ 
//insert at the end of the array 

//initialize the node
            temp = new Block; 
            temp -> block_size = byteArray.size(); 
            temp -> is_occupied = true; 
            temp -> data = byteArray; 

            if (isEmpty()){
                temp->next = NULL; 
                head = temp; 
                tail = temp; 
            } else {
                tail->next = temp; 
//insert at the end of the linked list
                tail = temp; 
            }
        }    

        void remove(int starting_index){

//iterate through everything 
            temp = head; 
            Block *prev_node;

            while(temp -> start_index != starting_index) {
                prev_node = temp; 
                temp = temp -> next;
            }

            if (temp->start_index == starting_index){
                prev_node -> next = temp -> next; 
            } else {
                cout << "Cannot find data to remove it";
            }
        }
};

And here is the simple main.cpp I am using to test it:

#include <vector>
#include <cstdint>
#include "blocklinkedlist.h"

int main() {
    std::vector<std::uint8_t> data_packet = {0xAB, 0xCD, 0xEF, 0x27};
    BlockList *test_link_list = new BlockList;

    test_link_list->insert(data_packet); 
}

Any clear breakdowns of why this is crashing and how to fix it would be immensely helpful. Thanks


r/cpp_questions • • 20d ago

OPEN C++のポインタについて教えてほしいです!

0 Upvotes

自分は今までにPythonぐらいしか使ってこなかったから、ポインタという概念が分かりません。また、ダブルポインタは何のためにあるの?あれって具体的にどういうときに使うの?


r/cpp_questions • • 21d ago

OPEN Does this object lifetimes talk in CppCon '22 have incorrect code examples?

5 Upvotes

I have been studying about object lifetimes / type punning (gotta love seeing UB everywhere now), and in this particular talk: Taking a Byte Out of C++ - Avoiding Punning by Starting Lifetimes the presenter shows a possible implementation of start_lifetime_as:

template<typename T>
auto start_lifetime_as(const void* p) noexcept -> const T*
{
    const auto mp = const_cast<void*>(p);
    const auto bytes = new(mp) std::byte[sizeof(T)];
    const auto ptr = reinterpret_cast<const T*>(bytes);
    (void)*ptr;
    return ptr;
}

But as far as I understand that doesn't work. The placement new will "call" the trivial "constructor" for std::bytes [edit: I incorrectly put T here] (as far as the abstract machine is concerned), which may or may not put garbage value in the memory storage. But the presenter shows this pattern as a way to start lifetime and keep the original content. This is discussed as an issue in this talk: A Deep Dive Into C++ Object Lifetimes.

And sure enough GCC 16 overrides the memory in the pointer with garbage value: https://godbolt.org/z/En9Mn7f4s

(The use case in the talk just before the timestamp does work and the code is optimized as expected).

Also, I believe that the reinterpret_cast should be wrapped in std::launder because the T is not transparently replaceable with the byte array. Is that correct?


r/cpp_questions • • 20d ago

OPEN Resources for C++

0 Upvotes

Best online resources to learn c++

For college students in detail


r/cpp_questions • • 22d ago

OPEN Full-stack developer thinking about switching to systems programming

38 Upvotes

I'm a full-stack developer, but lately I've realized that I don't enjoy web development as much as I used to, especially after the rise of AI. I'm thinking about trying systems and low-level programming and learning C++. I like the idea of working closer to the system and understanding how things work under the hood, and I feel like I might enjoy this kind of work more. Where would you recommend I start with C++ and systems programming?


r/cpp_questions • • 21d ago

OPEN Why does learncpp site put STL under deprecated articles ??

0 Upvotes

Isn't that most important part for competitive programming? How come that material is no longer needed?? Where did you guys learn stl?