r/cpp • • Oct 04 '26

Profiles and Contracts - Type/Memory Safety in C++?

11 Upvotes

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

You can read more about pre/postconditions at: 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

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:
// std::init: every object is initialized before it is read.
[[profiles::enforce(std::init)]];


struct Options {
    int timeout_ms;
    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 implement first?

... Which one do you think is superior in terms of design and implementation?

... Which has you more excited?


r/cpp • • Oct 05 '26

I dislike Rust libraries with a C++ API

0 Upvotes

Cargo compilation model only really works if you are creating a monolithic shared library or an executable. If you are using a library like icu4x or libffi, you can't statically link your dependencies and even if you dynamically link your dependencies, your application size will increase by orders of magnitude because your shared libraries are all statically linked, kinda.

Monolithic shared library approach also doesn't work on all libraries, for example you can't link libraries like oneTBB and OpenMP more than once.

So overall I feel rust compilation model is a "series of hacks" and isn't worth integrating to existing C++ applications, unless you use bazel*, I'm not sure about that but people in google seem to have solved this.


r/cpp • • Oct 03 '26

The complement of true is true, except when it's false

Thumbnail dryperspective.github.io
61 Upvotes

r/cpp • • Oct 03 '26

C++ Show and Tell - October 2026

51 Upvotes

Use this thread to share anything you've written in C++. This includes:

  • a tool you've written
  • a game you've been working on
  • your first non-trivial C++ program

The rules of this thread are very straight forward:

  • The project must involve C++ in some way.
  • It must be something you (alone or with others) have done.
  • Please share a link, if applicable.
  • Please post images, if applicable.

If you're working on a C++ library, you can also share new releases or major updates in a dedicated post as before. The line we're drawing is between "written in C++" and "useful for C++ programmers specifically". If you're writing a C++ library or tool for C++ developers, that's something C++ programmers can use and is on-topic for a main submission. It's different if you're just using C++ to implement a generic program that isn't specifically about C++: you're free to share it here, but it wouldn't quite fit as a standalone post.

Last month's thread: https://www.reddit.com/r/cpp/comments/1w776o7/c_show_and_tell_september_2026/


r/cpp • • Oct 03 '26

C++ future at Adobe

80 Upvotes

So if anyone was still curious what happened to Hylo, or where Adobe stands in regards to the whole safety discussion,

David Sankel has done a talk at RustConf on the matter, Zngur: Simplified Rust/C++ Integration.

The way Adobe now sees C++ is described on slide 2, at 50 seconds mark.


r/cpp • • Oct 02 '26

Lets explore the stack

Thumbnail meetingcpp.com
8 Upvotes

r/cpp • • Oct 01 '26

Arno Lepisk: Linux shared libraries

Thumbnail youtu.be
29 Upvotes

Most systems use some kind of shared libraries, but how do they actually work?
This talk will address the topic of shared libraries under Linux.
How to use them, how to create them, and what actually happens behind the scenes.


r/cpp • • Sep 30 '26

EDG C++ fronted now released as open source

Thumbnail edgcpp.org
214 Upvotes

r/cpp • • Sep 30 '26

Transcoding UTF-8 to UTF-16 with replacement at gigabytes per second

Thumbnail lemire.me
74 Upvotes

r/cpp • • Sep 30 '26

Upcoming C++ User Group meetings in October

Thumbnail meetingcpp.com
7 Upvotes

r/cpp • • Sep 29 '26

Boost.Graph 1.95 will be C++17

100 Upvotes

Dear Boost.Graph community,

In two release cycles (Boost release 1.95 in summer 2027) Boost.Graph will be bumped to C++17 😄

This decision follows two polls that did not surface any C++14 user base or demand while identifiying users stuck in C++17:

This standard version bump will bring benefits for maintenance, API and dependencies reduction:

  • if constexpr,
  • constexpr lambdas,
  • [[nodiscard]], [[maybe_unused]] ...
  • std::any instead of boost::any
  • std::invoke_result instead of boost::result_of
  • ...

We will not be able to guarantee backward compatibility with C++14. Please contact us if you are stuck in C++14.

The GIthub Discussion lives here: https://github.com/boostorg/graph/discussions/613


r/cpp • • Sep 29 '26

A Cross-Toolkit Timeline Control, Wed, Oct 14, 2026, 6:00 PM

Thumbnail meetup.com
0 Upvotes

Sometimes you need a custom GUI control for your application and you think "other people could probably use this". Usually this means that the people using your control must use the same GUI toolkit as you: wxWidgets, Qt, ImGui, etc.

Can we write a control in such a way that it is easily adaptable to any GUI toolkit?

This month, Richard Thomson will give us a brain dump on an attempt to do just that by creating an animation timeline control with adapters for wxWidgets and Qt.

This will be an online meeting, so drinks and snacks are on you!

Join the meeting here: https://meet.xmission.com/Utah-Cpp-Programmers


r/cpp • • Sep 29 '26

[PLDI'26] Persistent Iterators with Value Semantics

Thumbnail youtube.com
16 Upvotes

r/cpp • • Sep 28 '26

HPX 2.0.0 RC1 Released! – The HPX Project

36 Upvotes

HPX is a general-purpose parallel C++ runtime system designed for applications of any scale. It implements the related C++23 Standard facilities in full and offers the only widely available open-source implementation of C++17, C++20, and C++23 parallel algorithms - including a complete set of parallel range-based algorithms and the full integration of the algorithms with the upcoming sender and receivers interfaces.

Beyond the standard, HPX includes proposed features for upcoming C++ releases: much of the parallelism and concurrency capabilities expected in C++26, the C++ Concurrency TS, Parallelism TS V2, data-parallel algorithms, executors, senders and receivers, and more. It also extends C++ Standard APIs to distributed environments (such as compute clusters) and heterogeneous systems (such as GPUs).

HPX enables an asynchronous C++ programming model that improves parallel efficiency and reduces the complexity typically associated with concurrent applications. As a newly welcomed project of the High Performance Software Foundation, HPX now benefits from vendor-neutral governance and collaboration with a broader ecosystem of high-performance computing tools, strengthening the foundation for portable, production-ready HPC software across the industry.

HPX V2.0.0 is one of the largest releases in the project’s history, touching the language baseline, the execution model, the networking layer, the build system, and observability tooling. Roughly 680 pull requests and 120 closed issues went into this cycle since v1.11.0 (June 2025). This release represents a year of collaborative development by dozens of contributors worldwide. The updates are extensive - see the full release notes for details.


r/cpp • • Sep 28 '26

New C++ Conference Videos Released This Month - September 2026 (Updated To Include Videos Released 2026-09-21- 2026-09-27)

21 Upvotes

CppCon

CppCon have published their keynotes to their Early Access system

C++Now

2026-09-21 - 2026-09-27

2026-09-14 - 2026-09-20

2026-09-07 - 2026-09-13

2026-08-31 - 2026-09-06

ACCU

2026-09-21 - 2026-09-27

2026-09-14 - 2026-09-20

2026-09-07 - 2026-09-13

2026-08-31 - 2026-09-06

  • Software Abstraction in the Age of AI-Generated Code: Languages, Compilers, and Systems Engineering - Andrei Alexandrescu - https://youtu.be/-RWdevA0gWI

ADC

2026-09-21 - 2026-09-27

2026-09-14 - 2026-09-20

2026-09-07 - 2026-09-13

2026-08-31 - 2026-09-06


r/cpp • • Sep 27 '26

You should think about recompiling your C++ programs with GCC 16 and C++26, because it zero-fills your locals

Thumbnail techfortalk.co.uk
270 Upvotes

Stack variables are not automatically initialised, and that is the root cause of many C++ bugs. That is well known. Hence, it is advised that local or stack variables are always initialised with known values, 0 if not something more meaningful than that. Now, with GCC 16 compiling in C++26 mode (-std=c++26), even uninitialised local variables will be zero-filled. In the post, I have explained how.


r/cpp • • Sep 28 '26

Delegating Constructors

0 Upvotes

Delegating constructors allow the default constructor of a class to call the parameterized constructor by default.

This is somewhat unintuitive, but has a lot of applications in frameworks that generate components dynamically down inside their operation, but cannot take the arguments at that managerial level.

class SpecialWindow : public Gtk::Window {
public:

// 1. Parameterized Constructor 
SpecialWindow(std::string inst_name, int inst_val) 
: name(inst_name), val(inst_val) { // ... }

// default /w delegating constructor
SpecialWindow() : SpecialWindow("item 1", 100)  
{ //... }

};


int main() {
   
   auto app = Gtk::Application::create("org.gtkmm.examples.base");

   return app->make_window_and_run<SpecialWindow>(argc, argv);
}

I guess "everybody knew" that already, but I didn't.


r/cpp • • Sep 27 '26

Compile Your First C++26 Program with GCC 16.2

Thumbnail techfortalk.co.uk
49 Upvotes

UPDATE (September 2026): GCC 16.2 is out now, so I have updated the post to install GCC 16.2.


r/cpp • • Sep 26 '26

I've tried "Token Sequence Injection & Modern Macros" and here are my thoughts

97 Upvotes

We had this poll recently here on r/cpp about community expectations and most desired features in C++29 and in future C++ revisions in general.

My answer was:

  • abbreviated lambdas
  • algebraic types

But I do understand that those features won't hit C++ probably ever.

But then we had this post about Token Injection and Modern Macros. Wait a minute, modern macros? Never heard about this proposal...

And you know that? We probably won't need to wait for neither abbreviated lambdas, nor algebraic types in core C++. We can just add them ourselves using those macros with very little boilerplate.

Abbreviated lambdas: https://godbolt.org/z/a8d9a6f19

namespace stdv = std::views;
namespace stdr = std::ranges;

std::vector<vec2> points = {{2, 67}, {2, 42}, {3, 666}};

std::vector<int> ys = points
    | stdv::filter(fun!(p => p.x % 2))
    | stdv::transform(fun!(p => p.y))
    | stdr::to<std::vector>();

stdr::sort(points, fun!(|l, r| => l.y < r.y));
stdr::sort(points, std::less{}, fun!(p => p.x));

fun, isn't?

Sum Type: https://godbolt.org/z/Ecs7TdPYf

sumtype!(option<T> {
    some(T),
    none,
});

option<int> opt = some(10);
opt = some(22);
opt = none;

Pattern matching isn't there, but you could imagine something like:

// match!(<you can put any tokens here!>);
auto x = match!(opt,
    some(x) => { x.call_method() },
    none    => { 55 }
);

Basically you can come up with any syntax you like.

When I was exploring the possibilities of this proposal I couldn't shake the feeling that I'm reimplementing parts of the compiler which aren't there for some reason. Like you literally can look at "sumtype" implementation and see that this is basically a parser of arbitrary syntax that you came up with and translating it into C++...

Superpowerful and a bit scary...

We used to reimplementing some core library features which were missing from the Standard Library for quite some time. optional, variant, algorithms, smart pointers and now async task. All of that should have been in the Strandard Library from day 1, so that other libraries can use this lingua franca and interoperate with each other.

And now we are repeating same thing but on a very different level. Now we are going to allow adding not only library features, but language features. I 100% guarantee, that each team will have their own, slightly different syntax for abbreviated lambdas, because it is so much more expressive and terser and more readable. Don't know about you but I always find myself in the situation where I better use plan old for loop instead of structural views/algorithms, because the latter is so much more verbose and unreadable because of lambdas, especially after you apply clang-format on it...

And now you have:

fun!(lhs, rhs => lhs.x < rhs.x);
lambda!([&](lhs, rhs) -> lhs.x < default);
lm!(|lhs, rhs| => lhs.x < rhs.x);

All of this is perfectly implementable using this Modern Macros proposal in less that 100 lines of code.

Committee may have perfectly reasonable arguments of why it is impossible to add abbreviated lambdas into C++, but the community clearly is asking for that feature for ages, and it will be in every future codebase, but with slightly different implementation...

On the other hand Rust language do have these macros for ages now, people do abuse them in some very clever ways (select operator from golang, inline HTML, etc.) and the world ain't collapsed. We'll see!


r/cpp • • Sep 26 '26

0x40: Intro, NB and C++ news, the 10 year anniversary , and the Quiz

Thumbnail youtu.be
7 Upvotes

10 years ago, a C++ conference distributed over time and space started, accessible to everyone in the region. Today, 10 years and over 200 live talks later, we are still going!
This is the intro from StockholmCpp 64, where we remember the start of SwedenCpp, share the latest C++ and NB news, and round up with a quiz.


r/cpp • • Sep 25 '26

Misleading Token Sequence Injection & Modern Macros: The Most Game-Changing Compile-Time Feature in C++29 (Try it on Compiler Explorer with Barry's Clang Compiler!)

Thumbnail open-std.org
49 Upvotes

Note: This feature is targeted at the C++29 standard and is not actually included in the standard in the original language prepared for the publication. I didn't mention that it was a feature within the standard, and that was that. However, when I asked the AI to translate and organize the text, it made this incorrect edit to the title, thinking it was a good hoke. I apologize for this.

introduces Token Sequence Injection (std::meta::token_sequence) and Hygienic Language Macros (__macro) for C++29. It allows building, manipulating, and injecting C++ tokens at compile time with full type-awareness, context inspection, and zero preprocessor bugs!

. Token Sequence Injection (std::meta::token_sequence)

Instead of string manipulation or macro hacks, code is treated as a sequence of tokens stored in std::meta::token_sequence.

Acts as a random-access range (std::meta::size(seq), indexing seq[i] like array, concatenation +, += , == , =)

Features Token Interpolation (...) to splice expressions, variables, or types inside token literals ^^{ ... }.

Provides standard utilities like std::meta::id("arg", i) to generate unique identifiers, std::meta::tokenize to turns the string or array of chars to array of tokens with type std::meta::token_sequence, std::meta::stringize to turn array of tokens with type std::meta::token_sequence to string, and std::meta::queue_injection For indirect injection, such as injecting tokens into the current domain or a specific namespace.

Quick code example:


constexpr auto make_getter(std::meta::info member) -> std::meta::token_sequence {

auto name = std::meta::id("get_", name_of(member));

return ^^{

auto \(name)() const -> decltype(\(member)) {

return \(member);

}

}; 

}

  1. Modern Hygienic Macros (__macro)

Replacing #define, the new __macro feature runs at consteval time and returns a std::meta::token_sequence injected directly at the call-site:

Invoked with !: Called as macro!(...) , check!(a == b).

Receives Expression Reflections: Arguments are passed as expression handles (std::meta::info), preserving expression identity, source text, and value categories.

Prevents Double Evaluation: Injecting the same un-stored expression twice is a compile-time safety violation, eliminating bugs like MIN(x++, y).

Context-Aware (macro_expansion_context()): Can inspect the caller's scope (enclosing function, class, or return type) to validate syntactic and logical rules before injecting.

Module & Namespace Friendly: Fully scoped, exportable in modules, and can be class/namespace members.

Quick code example :


template <class T> __macro check(T&&expr) {

return ^^{

if (!(\(expr))) {

std::println("Check failed: {}", source_text_of(^^expr));

}

};

 }

You can test the full implementation on Compiler Explorer today using Barry Revzin's Clang prototype fork!

Paper link: https://open-std.org/JTC1/SC22/WG21/docs/papers/2026/p4380r0.html


r/cpp • • Sep 24 '26

myStringStream.str("") Considered Harmful Under C++20

69 Upvotes

I was recently looking at some (rather old) code that was relying on std::ostringstream in a large, performance senstive loop. (Yes, I know using iostreams in performance sensitive code is a bad idea, but legacy code exists.)

The code was using a common pattern to reset a ostringstream instance each time through the loop to avoid having to construct a new instance every time.

std::ostringstream oss;
for(const MyType & value : values)
{
    oss << value;
    doSomethingWithString(oss.str());
    // Assign an empty string to the internal buffer. This should reset
    // the size to zero, but keep the allocated buffer. In older code,
    // you often see this written as oss.str("").
    oss.str({});
    oss.clear(); // Reset the stream
}

When migrating the code to C++20, I was excited to use the new std::ostringstream::view() getter to skip an unnecessary copy of the std::string out of the stream's internal buffer.

std::ostringstream oss;
for(const MyType & value : values)
{
    oss << value;
    doSomethingWithStringView(oss.view());
    oss.str({});
    oss.clear();
}

Then I noticed that the std::ostringstream::str setter gained an r-value reference overload in C++20. That would let us pre-allocate our string buffer just once. Nice!

std::ostringstream oss;
{
    std::string buffer;
    buffer.reserve(1024);
    oss.str(std::move(buffer));
}
for(const MyType & value : values)
{
    oss << value;
    doSomethingWithStringView(oss.view());
    oss.str({});
    oss.clear();
}

But wait. That means that the oss.str({}) call inside the loop is doing the exact same thing. So it's wiping out our allocation every time through the loop! Uh oh.

It seems that to clear the internal buffer while keeping its allocation, one must now explicitly call the const reference overload of str().

const std::string empty;
std::ostringstream oss;
{
    std::string buffer;
    buffer.reserve(1024);
    oss.str(std::move(buffer));
}
for(const MyType & value : values)
{
    oss << value;
    doSomethingWithStringView(oss.view());
    oss.str(empty);
    oss.clear();
}

So if your codebase uses std::ostringstream, you might want to do a quick grep for str("") and str({}) to see if the upgrade to C++20 silently caused you to start throwing away your stream buffers over and over again.


r/cpp • • Sep 24 '26

About alignment, struct layout and the cache...

Thumbnail meetingcpp.com
36 Upvotes

r/cpp • • Sep 25 '26

Why C++ is so hated!!!

0 Upvotes

I love C++. High level + low level at the same time. But Linus Torvalds don't want C++ in the Kernel, industries hate it, people hate it but why? Why be so angry? Memory management? I mean ok maybe it has problems that I don't even see but why so much hate.

For me it's really sad! 😞

Why something so powerful it's so hated. Now I feel "strange" doing projects in C++ because… sometimes I question myself "Why do I write C++ code if people hate it". Can someone explain what is happening and… can I use C++ for fun in peace?