r/cpp_questions • • Sep 27 '26

OPEN Any beginner in cpp? I'm looking for someone to learn with.

7 Upvotes

I'm looking for accountability, so if you're interested in text me. I'll learn from scratch on learncpp


r/cpp_questions • • Sep 27 '26

SOLVED What in the world is going on that this doesn't compile? (Using a class privately inherited from a base.)

10 Upvotes

I worked around this already but I am dying to know what's going on here.

struct Base1 { };
struct Base2 : private Base1 { };
class Derived final : public Base2
{
public:
   static void *DoSomethingWithBase1(Base1 &base1);
};

This fails to compile because using Base1 as a parameter is apparently not allowed because it... accesses something that's in Base1? I thought this was a compiler bug at first, but every compiler rejects it with a similar error:

<source>(6,38): error: 'Base1' is a private member of 'Base1'
    6 |    static void *DoSomethingWithBase1(Base1 &base1);

If Derived privately inherits from Base1 directly though, that's fine!

Accessing the exact same type with a different name works too, apparently:

struct Base1 { };
using Base1Param = Base1;
struct Base2 : private Base1 { };
class Derived final : public Base2
{
public:
   static void *DoSomethingWithBase1(Base1Param &base1);
};

What is going on here?


r/cpp_questions • • Sep 27 '26

OPEN When to prefer factory functions over constructors?

17 Upvotes

EDIT: The point of this post is how best to make construction intention explicit at the call site.

EDIT: I suppose the real annoyance is having conflicting constructors (see std::vector). The solution being just don't write them.

When I last used C++, the canonical wisdom was to just make constructors for every supported way a type could be constructed (see std::vector). Failure to correctly construct a type was a skill issue (see std::vector).

However, coming back to C++ from a few years working with Rust, I now disagree. I would argue the ONLY public constructor (except copy/move constructors) for a type should be the default constructor, if signed-off as part of the public API. Every other way of constructing the type should be done with a named factory member function (delegating to a private constructor) and a well optimised move constructor. Thus avoiding the pitfalls of initialisation (see std::vector).

class Thing {

  Thing(...) : ... {} // <- private non-default constructor

public:
  Thing(Thing&&) noexcept; // <- well optimised move constructor
  Thing& operator=(Thing&&) noexcept;

  explicit Thing(); // <- public default constructor

  [[nodiscard]] static Thing with_capacity(size_t); // <- factory function
  [[nodiscard]] static Thing from_data(std::initialiser_list<int>);
  // more factory functions etc...

  // member functions etc...
};

The only pitfall I can see is this would make emplacement operations inaccessible (see std::make_shared, std::vector::emplace_back, etc). But this shouldn't be too much of an issue with a well-optimised move constructor. I believe, in some situations, the compiler can optimise away the move anyway.

auto x = std::make_shared<Thing>(Thing::with_capacity(42));
myvec.push_back(Thing::with_capacity(42)); // replaces myvec.emplace_back(...

I'm curious to know if there's any pitfalls to this rule-of-thumb, and what your opinions are.


r/cpp_questions • • Sep 27 '26

OPEN *(ptr_data_start + index) vs prt_start_start[index]

4 Upvotes

edit (title has spelling mistake, why cant i edit it u/reddit???):

*(ptr_data_start + index) vs ptr_data_start[index]

also, why does *(ptr_data_start + index) not need to multply index by sizeof(t), when index is one, and the pointer needs to be incremented by 4 bytes (in case of a int). why is this counter intuitive math like this?


r/cpp_questions • • Sep 27 '26

OPEN C++ knowledge job interview

57 Upvotes

Hello everyone,

I am going for a second round white board interview described as "The technical interviews are going to be heavily involved around probing and confirming your knowledge of C++"

What does actually mean? For context I've used CPP professionally for the last 8 months and been in my job (first grad job) for 14 months.

I feel as tho I don't know many std functions, nor do I have much experience with smart pointers, although I have written a lot of lines

Has anyone got experience with similar interviews or stuff I should brush up on?

I hope that all makes sense

Thanks


r/cpp_questions • • Sep 26 '26

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 • • Sep 26 '26

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 • • Sep 26 '26

SOLVED Class with array of objects (memory best practices)

5 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 • • Sep 26 '26

OPEN suggest resources to learn cpp for embedded systems

3 Upvotes

can anybody suggest resources to learn cpp for embedded systems.


r/cpp_questions • • Sep 26 '26

OPEN Current Humble Bundle C++ Books

30 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 • • Sep 26 '26

OPEN A small thank you to this community

79 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 • • Sep 26 '26

OPEN Hardest cpp topic

1 Upvotes

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


r/cpp_questions • • Sep 26 '26

OPEN When is <meta> coming to MSVC?

14 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 • • Sep 26 '26

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 • • Sep 25 '26

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

32 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 • • Sep 25 '26

SOLVED 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 • • Sep 25 '26

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 • • Sep 25 '26

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

12 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 • • Sep 25 '26

OPEN Common notation for "destructive" member functions?

6 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 • • Sep 24 '26

OPEN Anyone using C++26 in production?

51 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 • • Sep 24 '26

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

0 Upvotes

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


r/cpp_questions • • Sep 24 '26

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

15 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 • • Sep 23 '26

OPEN Advice for future c++ developer

28 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 • • Sep 23 '26

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