C++ - Reddit
226 subscribers
48 photos
8 videos
1 file
25.7K links
Stay up-to-date with everything C++!
Content directly fetched from the subreddit just for you.

Join our group for discussions : @programminginc

Powered by : @r_channels
Download Telegram
muopt: a C++17 micro-library for argument parsing

Hello! I wanted to share a project that I've been working on for the last few days, a small argument parsing library called muopt. It started from a quite popular Rust crate called lexopt that I use in one of my CLI Rust projects. I wanted something similar to lexopt and couldn't find it for C++, so I decided to write my own.

muopt is more of a tokenizer/lexer than it is a parser. It doesn't "connect" a value to its option and just views them as an argument. muopt is intended to be minimal and bare-bones. Below is a really simple example of muopt in action.

#include "muopt/muopt.hpp"
#include <iostream>

int main(int argc, char argv) {
muopt::Parser parser(argc, argv);

while (std::optional<muopt::Arg> arg = parser.next()) {
if (arg->islong("help"))
std::cout << "usage: example [--input FILE]\n";
if (arg->is
long("input"))
std::cout << parser.argvalue().valueor("") << '\n';
}
}

The code above will match the arguments --help and -h. Both will print out the usage message. It will also match --input=Hello or --input Hello and print out the value. The README has a deeper explanation on how muopt works and the repo has more examples.

muopt is still very early; it's not even released yet. I'm still debating on how to take on certain things, for example the arg_value() return type and how errors should be handled. Any suggestions are welcomed!

GitHub: https://github.com/secona/muopt

https://redd.it/1v6342h
@r_cpp
Profiles and Contracts - Type/Memory Safety in C++?

With the massive push for memory and type safety right now, there is a lot of talk in the C++ community about "profiles" and "contracts." They get grouped together a lot, but they solve entirely different problems.

Simply put: Profiles act as a set of global static rules that the compiler enforces to restrict the language itself. Contracts act as local conditions (both pre and post) which enforce your own API logic.

Here's some more breakdown between the two:

Contracts let you formalize your code's assumptions with pre, post, and contract_assert. To explain the difference between the three:

`pre` refers to preconditions, these are appended to function declarations and serve to evaluate predicates before the function body executes. If that condition evaluates to false, then the contract is broken. This can lead to things such as the program crashing or logging the error.
post refers to postconditions, which are also appended to function declarations but evaluate the state of your data after the function finishes running. They act as a guarantee to whoever called your function.
`contract_assert` lets the programmer specify properties of the program's state that are expected to be held up at certain points.

Here's a code example:

#include <iostream>

// Simple function showing where the contract keywords go
int divide_numbers(int numerator, int denominator)
pre (denominator != 0) // pre: Cannot divide by zero
post (result : result <= numerator) // post: Result must be <= numerator
{
// Internal assertion: Sanity check an internal assumption
contract_assert(numerator >= 0);

return numerator / denominator;
}

int main() {
// Compiles perfectly! However, at runtime, this triggers a precondition failure
// and terminates the program before ever hitting the internal contract_assert.
int output = divide_numbers(-10, 0);
std::cout << "Result: " << output << "\n";

return 0;
}

You can read about contracts in general at: [
https://en.cppreference.com/cpp/language/contracts](https://en.cppreference.com/cpp/language/contracts)

You can read more about pre/postconditions at: [
https://en.cppreference.com/cpp/language/functions/function\_contract\_specifiers](https://en.cppreference.com/cpp/language/functions/function_contract_specifiers)

For more information, check out open std: [
https://open-std.org/jtc1/sc22/wg21/docs/papers/2025/p2900r13.pdf](https://open-std.org/jtc1/sc22/wg21/docs/papers/2025/p2900r13.pdf)

Now for profiles!

Profiles essentially act as a set of global static rules which enforce the standards you have written, a good example of a profile is:

&#8203;

// std::init: every object is initialized before it is read.
[profiles::enforce(std::init)];


struct Options {
    int timeoutms;
    bool verbose;
};


bool parse
flag(const char arg, Options &out);


int run(int argc, const char argv) {
    Options opts;                       // error: 'opts.timeout_ms' is indeterminate
    int retries;                        // error: uninitialized


    for (int i = 1; i < argc; ++i)
        if (parse_flag(argv[i], opts))
            retries = 3;


    return opts.timeout_ms
retries;   // error: read before initialization
}

You can read more about profiles at: https://cpp-profiles.org/

Also, do consider checking open std: https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2025/p3589r2.pdf

You can even test out an example at: https://godbolt.org/z/n3TPjbqdY

So, with this information...


... What are your thoughts on contracts and profiles?

... Do you have a preference?

... Which should be implemented? Should both be implemented?

... Which one should we
No, -Wall -Werror Does Not Guarantee Detection of Conditionally Uninitialized Local Variables

There seems to be a misconception or lack of clarity about the usage of the compilation flags -Wall and -Werror and their ability to detect uninitialized stack variables. It depends. In this post, I will try to explore this further and explain when and how it is detected, and where it may not detect an uninitialized local variable and hence requires more caution while dealing with it. Consider the following code:

int main()
{
int value;
return value;
}

Compile this code as follows:

~/cpp_26_uninitialised$ g++ -std=c++23 -Wall -Werror test.cpp -o test
test.cpp: In function ‘int main()’:
test.cpp:4:12: error: ‘value’ is used uninitialized [-Werror=uninitialized]
4 | return value;
| ^~~~~
test.cpp:3:9: note: ‘value’ was declared here
3 | int value;
| ^~~~~
cc1plus: all warnings being treated as errors

So, with the use of the two compilation flags, `-Wall` and `-Werror`, the compilation fails, and you can then take corrective measures to address the uninitialized variable in the code.

Strictly speaking, -Wall enables the -Wuninitialized warning, and -Werror turns that warning into an error. However, *this is true only when the variable is uninitialized on every path to its use*, as `value` is here. It doesn't reliably work for a variable that is initialized on some paths and left uninitialized on others. Have a look at the following code:

// config_timeout_warning_test.cpp
#include <charconv>
#include <cstdio>
#include <string_view>

constexpr int default_timeout_ms = 1000;

// Reads "timeout_ms=<number>" from a device configuration line.
// The bug: when the key is missing, timeout_ms is never assigned.
[[gnu::noinline]] int read_timeout_ms(std::string_view config)
{
int timeout_ms;

constexpr std::string_view key = "timeout_ms=";

if (const auto pos = config.find(key); pos != std::string_view::npos)
{
const char* first = config.data() + pos + key.size();

const char* last = config.data() + config.size();

std::from_chars(first, last, timeout_ms);
}

return timeout_ms;
}

void open_device(const char* name, std::string_view config)
{
const int timeout_ms = read_timeout_ms(config);

if (timeout_ms <= 0)
{
std::printf("%-7s no timeout configured, using default %d ms\n", name, default_timeout_ms);
}
else
{
std::printf("%-7s timeout %d ms\n", name, timeout_ms);
}
}

int main()
{
// The empty configuration does not contain "timeout_ms=".
// Therefore, timeout_ms is returned without being initialized.
open_device("logger", "");

return 0;
}

Compile the code as follows:

~/cpp_26_uninitialised$ g++ -std=c++23 -O0 -g -Wall -Werror config_timeout_warning_test.cpp -o timeout_warning_test

The compilation succeeds without a single warning. Run Valgrind on it:

~/cpp_26_uninitialised$ valgrind --track-origins=yes ./timeout_warning_test
==2896379== Memcheck, a memory error detector
==2896379== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==2896379== Using Valgrind-3.18.1 and LibVEX; rerun with -h for copyright info
==2896379== Command: ./timeout_warning_test
==2896379==
==2896379== Conditional jump or move depends on uninitialised value(s)
==2896379== at 0x401268: open_device(char const*, std::basic_string_view<char, std::char_traits<char> >) (config_timeout_warning_test.cpp:31)
==2896379== by 0x4012D3: main (config_timeout_warning_test.cpp:45)
==2896379== Uninitialised value was created by a stack allocation
==2896379== at 0x401166: read_timeout_ms(std::basic_string_view<char, std::char_traits<char> >) (config_timeout_warning_test.cpp:10)
Which API design should my framework have?

right now in vexa(my game/graphics library) how you initialize window with a renderer is rather straightforward:

```cpp
\#include <vexa/vexa.hpp>

using namespace vexa;

int main()
{
Engine::Init(Engine::VIDEO);

Window window = Window().setSize({1280, 720}).setRenderer({}).create();

// ...

```
YES, it uses builder pattern, not very C++-ish but i like it.
However, there are two problems with it.
first one is that usually you have builder struct building to target type so that you dont need something like `.create()` that creates classic `if (m_created) ...` problem a.k.a two phase construction. but bigger problem that caused me two want to switch to this API style is about memory management. and it is now C++'s problem.. Even rust cant handle it, because this is what you tell it to do.
so lets dont talk too much:

```cpp

Engine::Init(Engine::FONT); // calls `TTF_Init();` by SDL_TTF behind the scenes

Font font = Font::Load("...");
...
Engine::Quit();
```

A Font has destructor running on scope exit. which means before font object gets destroyed on '}' Engine::Quit() so TTF_Quit() runs. You see, when Font object gets unloaded at scope end the subsystem is not live anymore, we get a segfault. to fix this i've made Engine have a Guard struct which does Engine::Quit() automatically. But then decided that this is not i want for my API. I would priorotize explicitness for the master deinitialization.

to fix this im thinking of new API design style:
```cpp
Window window = Engine::BuildWindow().setSize({1280, 720}).setRenderer().create();
```

where BuildWindow() returns WindowBuilder not a Window, unlike the previous(so bad) choice.
for fonts, as you might already guess:

```cpp
Font font = Engine::LoadFont("...");
```

which creates a font and returns reference to it, resulting Engine to know about font count and Quit or not based on that.

code: https://github.com/monjaris/vexa

https://redd.it/1x8gtg7
@r_cpp
offsetof(Header, fp);
_header.fp = [](void* p) {
S* const s = (S*) ((size_t)p & ~(size_t)1);
if (((size_t)p & 1) == 0) {
std::apply(s->_f, s->_a);
} else {
s->~S();
co::free(s, sizeof(S));
}
};
}

~S() = default;

struct Header {
uint32 magic;
uint32 off;
void (*fp)(void*);
} _header;
std::decay_t<F> _f;
std::tuple<std::decay_t<A>...> _a;
};

_p = co::alloc(sizeof(S), alignof(S));
runtime_assert(_p);
new (_p) S(std::forward<F>(f), std::forward<A>(a)...);
}
```

Key points:

- The `!std::is_convertible_v` in the template parameters ensures that simple lambda expressions such as `[](){...}` match the constructor for ordinary no-argument functions;
- `_header.magic` is always set to `0xdeadbeef`, which is used to distinguish the type of `closure`;
- `_header.fp` is the type-erased function pointer, and its parameter `p` is the `_p` in `closure`. Here, a tagged-pointer trick is used to distinguish between "calling the function" and "destroying the closure object", thereby eliminating the need for an additional function pointer to store the destructor and saving memory.

The implementation of `operator()` is as follows:

```cpp
void operator()() {
void* const p = _p;
if (p) {
if (((size_t)p & 15) != 0 || *(uint32*)p != 0xdeadbeef) {
((_F)p)();
} else {
(*(_FP*)((char*)p + ((uint32*)p)[1]))(p);
}
}
}
```

- If `_p` is not 16-byte aligned, or the first 4 bytes of the memory pointed to by `_p` are not `0xdeadbeef`, then `_p` is cast to an ordinary no-argument function pointer and executed directly;
- Otherwise, the `_header.fp` described in the previous code is obtained according to the memory layout and executed.

An example usage of `closure` is as follows:

```cpp
#include "co/print.h"
#include "co/closure.h"

void f() {
co::println("f()");
}

int main(int argc, char** argv) {
co::closure c(f);
c();

co::closure d([]() {
co::println("[]() {}");
});
d();

co::closure e([](int v) {
co::println("e called: ", v);
}, 8);
e();

return 0;
}
```

The complete code implementation can be found in [co/closure.h](https://github.com/idealvin/coost/blob/master/include/co/closure.h). The code in this article is for research and reference only. Discussion is welcome.

https://redd.it/1xd133x
@r_cpp
Is loop unrolling one of the speed booster

Long story short, I tried to check performance of C++ vs python by checking if file exists.

Here after - naive loop unrolling, seems the C++ code speed boosted. Please suggest other hacks/suggestions to make C++ run faster. Also if any books, links, github - please. I request C++ professionals


import os.path

FILES_DIRECTORY : str = "data"

def missing_parser(_skip_index: int, _max_limit : int = 400):
_cur_index : int = _skip_index
_max_limit = _skip_index + 400
while _cur_index < _max_limit:
for j in range(_cur_index, _cur_index+100):
if os.path.exists(os.path.join(FILES_DIRECTORY, str(j)+".pkl")):
print("Path exists",str(j)+".pkl")
else:
print("Missing ",str(j)+".pkl")
_cur_index += 100

missing_parser(1)


## Python time taken

real    0m0.750s
user 0m0.011s
sys 0m0.108s


#include<iostream>
#include<fstream>
#include<string>
#include<filesystem>

#define FILE_DIRECTORY = "data"

void check_files(unsigned _start, unsigned _end){

std::string file_name;

for(unsigned k=_start; k<=_end; k++){
bool file_exists = false;
std::string filename = "./data/"+std::to_string(k)+".pkl";

file_exists = std::filesystem::exists(filename);

if(file_exists){
std::cout<<"File Exists\n";
}else{
std::cout<<"File not exists\n";
}
}
}

int main(int argc, char const *argv[]){


check_files(1, 400);

return 0;
}


C++ default build, time taken

real    0m0.706s
user 0m0.004s
sys 0m0.080s


Default compilation was slower than python, but after adding "Release" flag on, the CMake generated build, faster by 0.10 seconds.

Now the final part

#include<iostream>
#include<fstream>
#include<string>
#include<filesystem>

#define FILE_DIRECTORY = "data"

void check_files(unsigned _start, unsigned _end){

std::string file_name;

for(unsigned k=_start; k<=(_end/10)+1; k++){
bool file_exists[10] = {0};

std::string filename1 = "./data/"+std::to_string(k)+".pkl";
std::string filename2 = "./data/"+std::to_string(k+1)+".pkl";
std::string filename3 = "./data/"+std::to_string(k+2)+".pkl";
std::string filename4 = "./data/"+std::to_string(k+3)+".pkl";
std::string filename5 = "./data/"+std::to_string(k+4)+".pkl";
std::string filename6 = "./data/"+std::to_string(k+5)+".pkl";
std::string filename7 = "./data/"+std::to_string(k+6)+".pkl";
std::string filename8 = "./data/"+std::to_string(k+7)+".pkl";
std::string filename9 = "./data/"+std::to_string(k+8)+".pkl";
std::string filename10 = "./data/"+std::to_string(k+9)+".pkl";

file_exists[k] = std::filesystem::exists(filename1);
file_exists[k+1] = std::filesystem::exists(filename2);
file_exists[k+2] = std::filesystem::exists(filename3);
file_exists[k+3] = std::filesystem::exists(filename4);
file_exists[k+4] = std::filesystem::exists(filename5);
file_exists[k+5] = std::filesystem::exists(filename6);
file_exists[k+6] = std::filesystem::exists(filename7);
file_exists[k+7] = std::filesystem::exists(filename8);
file_exists[k+8] = std::filesystem::exists(filename9);
file_exists[k+9] = std::filesystem::exists(filename10);

if(file_exists[k]){
std::cout<<k<<"File Exists\n";
}else{
std::cout<<"File not exists\n";
}

if(file_exists[k+1]){
std::cout<<k<<"File Exists\n";
}else{
std::cout<<"File not exists\n";
}

if(file_exists[k+2]){
std::cout<<k<<"File Exists\n";
}else{
std::cout<<"File not exists\n";
}

if(file_exists[k+3]){
std::cout<<k<<"File Exists\n";
}else{
std::cout<<"File not exists\n";
}

//so on, removed due to code length

}
}

int main(int argc, char const *argv[]){

check_files(1, 400);

return 0;
}


The final version is faster by 0.2 second.

when measured by $ time command,

real    0m0.512s
user 0m0.000s
sys 0m0.055s


https://redd.it/1xnoq3m
@r_cpp
Potential GCC 16 bug: annotations disappear on nested class declarations inside class templates

Im playing around with reflection (GCC16) and I ran into the following problem:

When using `std::meta::define_aggregate`to complete an annotated nested class, the annotation is removed, iff the enclosing class is templated.

Below is a minimal reproducible example ([Godbolt link](https://godbolt.org/z/dGTsea7ad)).

I would expect both assertions to succeed, but they don't. There is also [GCC PR124399](https://gcc.gnu.org/bugzilla/show_bug.cgi?id=124399), which addresses a related problem, but I'm not sure if this is the *same* underlying problem.

Is this a bug, or am I overlooking/misunderstanding some template instantiation rules?

#include <meta>

// Works: ordinary forward declaration.
struct [[=42]] Ordinary;
static_assert(std::meta::annotations_of(^^Ordinary).size() == 1);

// Fails: forward declaration inside a class template.
template <typename T>
struct Outer {
struct [[=42]] Inner;
};

static_assert(sizeof(Outer<int>) > 0);
static_assert(std::meta::annotations_of(^^Outer<int>::Inner).size() == 1);

**Context:** I'm experimenting with rust-like `derive(debug)` functionality using annotations, combined with structural type transformations (similar to AoS to SoA). I originally encountered this while trying to propagate annotations to a generated type, before reducing it to the example above.

https://redd.it/1xovcbd
@r_cpp
MSVC 14.52, migration code to C++23

Now that MSVC 14.52 is released with Visual Studio 2026 18.12 I have tried to rebuild the project I am working on with /std:c++23. Thx for finally releasing C++23 support.

I have previously used /std:c++23preview and my assumption was that the migration would be effortless. But not so. So this is a heads up.

Most of the issues I have ran into is related to C++23 and how incomplete types are used in headers. So C++23 changed so that std::uniqueptr destructor now is constexpr. This means that I have to add/move destructor to .cpp source file.
For reference, see Github issues
https://github.com/microsoft/STL/issues/4215 and https://github.com/microsoft/STL/issues/4417

But I also have issues with code like:

// Forward declaration
class Foo;

class A
{
public:
void Add(const Foo & foo ) {
foos.pushback(foo); }

private:
std::vector<Foo>
foos;
};

class Foo
{
};

Godbolt with MSVC 14.51 and /std:c++23preview - https://godbolt.org/z/ae5M53fK1
Works also perfectly well in GCC 16.2 -std=c++23 - https://godbolt.org/z/rhEM5MMhG

As of this writing MSVC 14.52 and /std:c++23 is not yet available on Godbolt.

But I get error C2139: 'Foo': an undefined class is not allowed as an argument to compiler intrinsic type trait 'isnothrowconstructible'

A tad annoying.

https://redd.it/1xtc3a4
@r_cpp
std::contracts::controls::enforced

From P4451R2,

\#include <contracts>
int f(int x)
pre<std::contracts::controls::enforced>(x > 0)
post<std::contracts::controls::enforced>(r : r > 0)
{
contract_assert<std::contracts::controls::enforced>(x > 0);
return x;
}

Long, 3 levels deep namespace? And

\> Because the label is found by ordinary name lookup, a namespace alias or a using-directive works
as well:
namespace scl = std::contracts::controls;

Same issue as with C++11 UDL: inconvinient to use, especially in headers, since include + alias is required - aliases will not make it better, in my opinion.

That makes me sad. Am I the only one?

https://redd.it/1y31isw
@r_cpp
제가만든c++로만든ln이빠를까요 c++의내장함수ln이더빠를까요

x = 1917

custom\_ln (직접 구현한 커스텀 함수) : 7.5585167430456446,0.0000000000000000)

std::log(c++내장함수) : (7.5585167430456446,0.0000000000000000)

절대 오차 : 0.0000000000000000e+00

custom\_ln\_minimax\_nodiv : 113.983 ms

std::log : 119.788 ms

sink : 1511703348.185087






만약코드가궁금하다면

#include <iostream>
#include <cmath>
#include <bit>
#include <chrono>
#include <array>
#include <iomanip>
#include <limits>


struct LutEntry {
double inv_m;
double ln_m;
};


constexpr std::array<LutEntry, 64> make_ln_lut() noexcept {
std::array<LutEntry, 64> lut{};
for (int k = 0; k < 64; ++k) {
double m = 1.0 + (static_cast<double>(k) + 0.5) / 64.0;
double inv = 1.0 / m;


double u = (m - 1.0) / (m + 1.0);
double w = u * u;
double term = u;
double sum = 0.0;
for (int n = 1; n <= 25; n += 2) {
sum += term / static_cast<double>(n);
term *= w;
}
lut[k] = { inv, 2.0 * sum };
}
return lut;
}


inline constexpr auto LN_LUT = make_ln_lut();


inline double custom_ln_minimax_nodiv(double x) noexcept {
constexpr double LN2 = 0.693147180559945309417232121458;


uint64_t bits = std::bit_cast<uint64_t>(x);
int64_t B = static_cast<int64_t>((bits >> 52) & 0x7FF) - 1023;
uint64_t mantissa_bits = (bits & 0x000FFFFFFFFFFFFFULL) | 0x3FF0000000000000ULL;
double A = std::bit_cast<double>(mantissa_bits);


uint64_t idx = (bits >> 46) & 0x3FULL;
const auto& entry = LN_LUT[idx];


double t = A * entry.inv_m - 1.0;
double t2 = t * t;


constexpr double c1 = 1.00000000000000000;
constexpr double c2 = 0.50000000000000000;
constexpr double c3 = 0.33333333333333333;
constexpr double c4 = 0.25000000000000000;
constexpr double c5 = 0.20000000000000000;
constexpr double c6 = 0.16666666666666666;
constexpr double c7 = 0.14285714285714285;


double odd = c1 + t2 * (c3 + t2 * (c5 + t2 * c7));
double even = c2 + t2 * (c4 + t2 * c6);
double ln_1p_t = t * (odd - t * even);


return static_cast<double>(B) * LN2 + entry.ln_m + ln_1p_t;
}


int main() {
constexpr int ITERATIONS = 100'000'000;
volatile double sink = 0.0;


std::cout << "양수 x를 입력하세요 (종료하려면 q 또는 Ctrl+D):\n";


double x = 0.0;
while (true) {
std::cout << "\nx = ";
if (!(std::cin >> x)) {
if (std::cin.eof()) break;
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
std::cout << "숫자만 입력해 주세요.\n";
continue;
}


if (x <= 0.0) {
std::cout << "양수(> 0)를 입력해 주세요.\n";
continue;
}


double acc1 = 0.0;
auto t0 = std::chrono::high_resolution_clock::now();
for (int i = 0; i < ITERATIONS; ++i) {
acc1 += custom_ln_minimax_nodiv(x);
}
auto t1 = std::chrono::high_resolution_clock::now();


double acc2 = 0.0;
auto t2 = std::chrono::high_resolution_clock::now();
for (int i = 0; i < ITERATIONS; ++i) {
acc2 += std::log(x);
}
auto t3 = std::chrono::high_resolution_clock::now();


sink = acc1 + acc2;


std::chrono::duration<double, std::milli> custom_ms = t1 - t0;
std::chrono::duration<double, std::milli> std_ms = t3 - t2;


std::cout << std::fixed << std::setprecision(3);
std::cout << "custom_ln_minimax_nodiv : " << custom_ms.count() << " ms\n";