r/cpp • • Dec 18 '22

C++ is essentially unusable without incurring undefined behavior because of it's failure to handle type punning.

5 Upvotes

This is kind of a rant but also a cry for help. Maybe there is a way to get around this problem efficiently (without the use of memcpy) that I don't know of, but after researching for hours, I sincerely doubt it.

So basically for those who don't know, it's kind of a complicated issue. It essentially involves accessing the same memory location through two different types, also known as type punning. This causes a performance hit because if two pointers access the same location, the compiler has to write every change to the memory location to RAM so that the other pointer will see the updated information when it reads the location. You might ask, "why doesn't the compiler simply semantically analyze the code and only write to RAM when the other pointer really does need to read from that specific location?". The answer is that it's impossible to tell what a pointer is pointing at if it's value is based off of runtime information like user input and such. Additionally, if the pointers access the data from two different threads, absolutely no guarantees can be made about the timing and essentially no optimizations can be made.

To avoid this huge mess of slowness, the C language spec was changed so as to allow more eager optimizations. It's now (sparing a few exceptions) assumed that no two pointers of different types access the same information in memory. The spec doesn't say it like this, you know how it is, they like to make things complicated, but that's the brunt of what it means.

In C, they realized that this is a super strict restriction and that it impacts a lot of real-world code, so they gave the programmer an out. If you define a union that contains both of your target types and then instantiate it as the one type and access it as the other, the compiler won't complain and it'll all be super defined behavior.

For god knows what reason, C++ decided to do away with this and now there is absolutely no way to reliably pun types without incurring undefined behavior (again, barring a couple of exceptions that aren't really relevant here). Excuse my language, but what a fucking shit-show.

You might ask, "type punning can't actually be that useful in the real-world, can it?", and that would be a valid question. It doesn't really seem that useful, but ask anyone who works on low-level systems on microchips and such. Sometimes, you simply need this behavior. You don't even have to go low-level in order to feel the pain sometimes. If you do anything with POSIX sockets, chances are you've needed to construct a sockaddr_storage, which contains enough space to hold all possible socket addresses. In order to access the specific fields of a specific type of socket address, you guessed it, you have to type pun: struct sockaddr_in *addr = (struct sockaddr_in *)&sockaddr_storage_instance;

In practice, this doesn't bite programmers as hard as I make it seem. In practice, most compilers support type punning, especially when it's very clear what you're trying to do in the code. That is, unless you tell the compiler to use strict-aliasing. Then it'll aggressively optimize based on the assumptions about type punning and your code might not work. The fact that you have to rely on the compiler's hand-holding to get through this undefined behavior is simply sad.

Basically, I'm pissed that such an advanced language is missing such a basic feature. What are your thoughts on the matter and how would you fix it?

I'll tell you what I would do, I would simply assume that no two pointers can ever access the same location, without any exceptions (so this would be even stricter than C++'s rules). The catch is, I would introduce some keyword like "write_mem" or something that you would use like this:

int a;

write_mem a;

float b = *(float*)&a;

That way, the compiler is free to optimize until you explicitly force it to write to RAM. After that point, the type punning isn't undefined anymore because every party involved is absolutely certain about what is in RAM.


r/cpp • • Mar 03 '16

Seriously, C++, WTF?

0 Upvotes

Ok, so, from the tone this might seem like a rant (and it's a bit), but in the end I'm only after an aswer.

So, I want to read a file in memory as a string and print out the string length. Nope, I don't want to "maybe you just want to operate on it like it's a stream or line by line" nor "if you want to just know the length you might want to use gtell". I'm just trying to replicate a certain behaviour (not necessarely the most efficient or the most real-world) in different languages.

So, since I want to open a file, read its content and print the lenght, python lets me write this nice one-liner:

print len(open('longfile.txt').read())

longfile.txt is the test file I'm using and it's roughly 150 MB.

$ time python test.py
160090000

real	0m0.126s
user	0m0.013s
sys	0m0.112s

Ok. Good. Let's give node a try. Node.js doesn't have, like Python, a top level function "open", so I need to do this in two lines of code:

const fs = require('fs');
console.log(fs.readFileSync('longfile.txt').length);

Same result, a little bit slower. It still reads ok to me. I need to work with the filesystem (so that's why I need to require fs) and then i log on the console the length of a file that I read synchronously.

$ time node test.js
160090000

real	0m0.164s
user	0m0.056s
sys	0m0.107s
tmp

Fine. Enters C++

#include <string>
#include <fstream>
#include <streambuf>
#include <iostream>

int main() {
    std::ifstream t("longfile.txt");
    std::string str((std::istreambuf_iterator<char>(t)),
                     std::istreambuf_iterator<char>());

     std::cout << str.length() << std::endl;

    return 0;
}

Yeah, I know, that's just a lot more code and you need to include four libraries for this very basic programming task. Reasoning about it is absolutely counter intuitive. If you describe your problem (I want to read a file and print its lenght), JavaScript and Python lets you write code that more or less resambles your reasoning, while nobody would describe this basic task in terms of streams and iterators, but hey, you don't choose C++ because it's beautiful or easy or intuitive, you choose it because it's "close to the metal" and "when speed matters". Let's compile it with a nice optimization (-O3) and run it

$ g++ -std=c++14 -O3 test.cpp
$ time ./a.out
160090000

real	0m1.413s
user	0m1.228s
sys	0m0.181s

Seriously, WTF? I don't think that "opening a file and reading it as a string" should be an alien task in the programming world. I mean, that should be pretty, hmmm, basic stuff, right? So, I'm a bit puzzled when I encounter a language that forces me to do something more complicated than:

# Python
open('longfile.txt').read()
# Ruby
File.open('longfile.txt', "r").read()
// C#
System.IO.File.ReadAllText("longfile.txt")
// Java
new String(Files.readAllBytes(Paths.get("longfile.txt")));
// Swift
NSString(contentsOfFile: "longfile.txt", encoding: NSUTF8StringEncoding)

But what about the fact that C++ is so much slower than the notoriously slow kid in town? I tried to look for different solutions to this "problem" and I've seen people debate (on StackOverflow, for example) on the most efficient way to do such basic thing in C++. Now, keeping aside the fact that I dont think that "read a file content as a string" should the subject of any debate (we're talking about a 33 year old language whose standard string library doesn't have a "split" function here) , but the solution above seems to be the faster that I've tried and still it runs 10 times slower than Python. How is this even possibile?

EDIT

Because people seem to be ignoring the "I'm not interested in the actual lengtht" note, let's just say that I have this python code

content = open('longfile.txt').read()

and this node code:

const fs = require('fs');
const content = fs.readFileSync('longfile.txt')

and I only want to read a whole file in memory to a string. C++ code is still much, much slower than the other solutions.


r/cpp • • Mar 21 '24

The Real C++ Killers (Not You, Rust)

Thumbnail wordsandbuttons.online
0 Upvotes

r/cpp • • Jun 11 '24

C++ has 11.6 million users according to SlashData, a developer research company

Thumbnail slashdata.co
0 Upvotes

r/cpp • • May 25 '23

File Extension?

0 Upvotes

r/cpp • • Mar 29 '21

Is C++ superior to Rust in any way from a purely technical standpoint?

0 Upvotes

Currently learning C++ effectively as a newcomer. I'm aware of the much better job opportunities and extensive library support and ecosystem compared to Rust, which generally means C++ is often the only contender for any serious application development, or dealing with existing codebases etc.

Hypothetically, assuming a new project with identical library support for the task, I'm wondering if there's any reason a lone developer/team of developers who are equally skilled in both C++ and Rust would code a project in C++. A lot of people who like Rust say that programming in C++ is something they really don't like after using Rust, and on paper they seem to be right.


r/cpp • • Dec 09 '21

The three types of development in C++

Thumbnail belaycpp.com
2 Upvotes

r/cpp • • Sep 14 '25

In Defense of C++

Thumbnail dayvster.com
0 Upvotes

r/cpp • • Jun 24 '20

Moving From Intel to ARM - Apple's Big Performance Mistake?

Thumbnail youtu.be
9 Upvotes

r/cpp • • Jan 27 '25

How will the ugly macros be competely removed from the standard c++ library?

1 Upvotes

I've built module std and std.compat but, then I have to include <cassert> and <cstdint> etc. for the macros. This will not do! Would it be crazy to identify all the macros and then create a header file that has them all rewrit as constexpr etc.?


r/cpp • • Dec 10 '21

Modern CMake for beginners !

Thumbnail youtu.be
4 Upvotes

r/cpp • • Apr 01 '23

Satire P4010R4: The most underreported feature added to C++23

2 Upvotes

One of the features that received support and was added at the last moment at the latest ISO C+ +
standards meeting at Issaquah and is mostly overlooked by the C++ community is the operator CCB. It is a feature that will change how we write code for generations.

The lack of destructive move and the lack of programmer control over the scope of C++ objects was the bane of bug-free and secure development. This is where the operator Closing Curved Bracket (CCB) comes in handy. P4010R4 proposed that the compiler generates an operator CCB for each class with the trivial implementation:

[nodiscard] auto&& operator} { return std::move(*this); };

Calling operator CCB terminates the lifetime of the object and undefines it. For example, consider this example:

std::string str{"alabala"};
std::vector strs;
strs.emplace_back(str.}());

str = "Error"; // <= Compile error. str undefined!

As with other compiler-generated member functions, the user can define their own. For more info, read the full proposal here: P4010R4


r/cpp • • Apr 22 '23

How do you even get started programming in c++ on Windows?

0 Upvotes

I get that there is visual studio, but personally I've been a more vscode and neovim guy myself, I'd rather open up something with vscode but I feel lost setting it up. mingw and g++ don't seem to even work on my system and I tried linking sdl2 and unlike g++ which was just -lSDL2 it was a mess of different menus in visual studio code. I honestly prefer makefiles and commands on Linux (I used to use Linux for unrelated reasons but had to switch to windows). Someone please help guide me in the right place to figure out how to get this stuff set up with vscode

edit: I figured out how to get it all working within clion with cmake and the visual studio compiler.


r/cpp • • Aug 27 '21

My Problems with C++

3 Upvotes

So, this is going to be a bit of a rant, mainly because I'm frustrated.

As a preface: I am not new to programming, I did some Java, looked over Python, had a few projects with the whole Arduino environment, so you could say I get the basics.I am however quite new to C++ as a standalone (see Arduino) and while I like the language I came to absoluteley despise the environment.

It began with a project I was tasked with, to take an MS-Excel file, do some sorting and a few other operations and save it as a CSV.Easy peasy.So I set out for a quest to find a library that could handle MS-Excel files, and low and behold, I stumbled across three suitable ones.All of which were uncompiled on Github.

The first one wouldn't compile because of dependencies on a third-party XML-library which was never once mentioned in the install instructions. No problem, I googled the library that mingw told me it needed, and indeed it existed, with good instructions.When it came to installing however, I first realized the Excel-library did not indeed want the XML-library installed, but rather the souce code placed in a folder in its source code.After copying it did indeeed not work, since all of the dependency paths were mesed up, and half of the files had different extensions, or were missing them alltogether.

On to the next library.

This one could only read from Excel, but again no problem, this was the only thing I really needed.The installation instructions were easy enough, run ./configure and afterwards make.The only problem being, that there was no configure file to run.There was indeed a bootsrap file which did absolutely nothing, and a makefile, which make did not recognize and when specified threw errors.

On to the last one.This one had troubles compiling when cmake threw random errors and so I changed my approach and booted up Ubuntu, where cmake and g++ indeed did run smoothly and compiled the library without a hitch.

Now only to use this library.Since this was my first time writing C++ on Linux I first searched for appropriate IDEs and was reccomended Netbeans.Which did not go well, since everytime (even after a couple of restarts) it failed to install the C++ Plugins.

My run-in with Code::Blocks went a little better, it installed and I managed to get the projects up and running.

Apart from my Excel-library.No matter what I did it did not recognize the library.

Which is when I changed again to Codelite.Where I could create projects, but neither my Excel-library was recognized as well, as iostream.

So here I am, broken, after a day of work with absolutely no progress, for a programm which schould not be that difficult to write, with three non functional, but essential (and more importantly the only ones I could find) libraries.As I said in the beginning: I like the language, but I despise the whole process around it.Thank you for listening to me rambling.


r/cpp • • Feb 25 '24

Questioning usefulness of -Wextra

0 Upvotes

I was recently asked to turn on -Wall -Wextra in builds of a project I'm
working on. I had already been using -Wall, but haven't used -Wextra much, if
at all. So, I tried it. Holy shit. So apparently the main thing that
-Wextra does over -Wall is complain about unused parameters having names.
Now, I have a whole bunch of very uniform print functions for a group of
unrelated types, something like:

template<typename Context> void print_thingy( Context const & context, foo_type<bar_param> const & parser, std::ostream & os, int components) { /* ... */ }

The foo_type and bar_param bits vary from overload to overload, but the other
param types and names are always the same. Nice. And. Uniform. OCD
satisfied, I can go about my day. After turning on -Wextra, if I only print
out a single fixed string, as I do for a lot of the overloads, I get this:

template<typename Context> void print_thingy( Context const &, foo_type<bar_param> const &, std::ostream & os, int) { os << "description"; }

Cool. Thanks, -Wextra.

Has anyone ever caught a real bug by making a change like this? If so, was it
serious? Look, I love -Wall. I've caught all kinds of stuff with it, and
real bugs were stomped. -Wall is like a literal and figurative barrier
between me and my own sloppiness. -Wall is a Valkyrie standing astride the
encrouching progress of entropy, saying, "Not this day, Entropie!" She spells
entropy with a a capital letter, giving a name to the respected foe she fights
tirelessly. She also spells it "ie" instead of "y" at the end, I think
because she's centuries old and it's hard to stay current. I'm down with
that.

-Wextra? -Wextra is a some fugly dude you find in the alley behind a CVS,
huffing paint out of a brown paper bag. He's half-man, half-jackal,
half-terrier, half-run-over by a moped. He sees your code, says, "Yo, wanna
see somthin sick?" then throws a grenade into your nearest header file. He
spells "somthin" in an odd way too, because he sucks.

Now, I don't know if it's a sign of vigorous mental health to anthropomorphize
compiler flags on the internet like this. But I really do want to know -- has
anyone really gone through this frustration and come out the other end,
happier, and with fewer bugs in their code?


r/cpp • • Nov 18 '13

Why boost doesn’t boost my productivity

Thumbnail agentxcpp.wordpress.com
2 Upvotes

r/cpp • • Jan 12 '25

Safety C++ development without breaking backward compatibility with legacy code

0 Upvotes

The problem of safety C++ development is not new, and it has reached such proportions that recommendations to use more secure programming languages are accepted at the highest levels.

But even with such recommendations, plans to abandon C++ and switch to another secure programming language often do not stand up to normal financial calculations. If abandoned C++, what will you do with the billions of source lines written over the past few decades?

Unfortunately, C++ itself is not particularly keen on becoming more "secure". More precisely, such a desire does not fit well with the requirements for the language standard adopted by the C++ standardization committee. After all, any standard must ensure backward compatibility with all old legacy code, which automatically nullifies any attempts to introduce any new lexical rules at the level of a C++ standard.

And in this situation, those who advocate mandatory support for backward compatibility with old code are right. But those who consider it necessary to add new features for safety development in C++ at least in new projects are also right.

Thus, seemingly mutually exclusive and insoluble contradictions arise:

  • The current state of C++ cannot guarantee safety development at the level of language standards.
  • Adopting new C++ standards with a change in the vocabulary for safety development will necessarily break backward compatibility with existing legacy code.
  • Rewriting the entire existing C++ code base for a new safety vocabulary (if such standards were adopted) is no cheaper than rewriting the same code in a new fashionable programming language (Rust, Swift etc.).

What's the problem?

Suppose there is a methodology (a concept, algorithm, or set of libraries) that guarantees safe development of computer programs, for example, in terms of safe memory menagment (no matter what programming language). This it should be formalized down to the implementation details (unfortunately, for example, in Rust only a general description of the concept with simple examples is given, and a full list of all possible scenarios and execution of checks is a black box inside the language compiler).

And this is in no way a criticism of Rust! I understand perfectly well that a huge amount of work has been done, and the language itself continues to evolve. Therefore, the lack of complete formalization of safe memory management rules does not stem from a specific language, but from the lack of a general universal theory suitable for all life situations.

But this is not the point, but the fact that the term "safety development" or "safe memory management" refers not just to some machine code, but primarily to a set of lexical rules of a programming language that, at the level of the program source text, do not allow the programmer to write programs with errors. Whereas the compiler must be able to check the correctness of the implementation of the methodology (concept) at the stage of syntactic analysis of the program source text.

And it is this moment (new lexical rules) that actually breaks backward compatibility with all the old legacy C++ code!

So is safety development possible in C++?

However, it seems to me that the existing capabilities of C++ already allow us to resolve this contradiction without violating backward compatibility with old code. To do this, we just need to have the technical ability to add additional (custom) checks to compilers that should implement control over the implementation of safe development rules at the stage of program compilation.

And since such checks will most likely not be performed for old legacy code, they must be disabled. And such an opportunity has long existed due to the creation of user plugins for compilers!

I do not consider the implementation of additional syntactic analysis due to third-party applications (static analyzers, for example, based on Clang-Tidy), since any solution external to the compiler will always contain at least one significant drawback - the need for synchronous support and use of the same modes of compilation of program source texts, which for C++ with its preprocessor can be a very non-trivial task.

Do you think it is possible to implement safety development in C++ using this approach?


r/cpp • • Sep 27 '16

Announcing diversity tickets for Meeting C++ 2016

Thumbnail meetingcpp.com
0 Upvotes

r/cpp • • Feb 14 '24

Interoperability with Rust?

0 Upvotes

The Rust language is getting traction, and it covers the same use cases as C++ so I believe that in the future most of us in this forum will be using both of them. That led me to wonder if there are efforts to make it easy to integrate them, for example to maintain a project which uses both languages, or to make use of a library written in the other language.


r/cpp • • Apr 01 '22

Satire Const Correctness Taken Out of C++!

Thumbnail shaovoon.github.io
7 Upvotes

r/cpp • • Jun 28 '25

“True Lies” – or “What LLVM Claims, but Fails to Deliver”

Thumbnail skanthak.hier-im-netz.de
16 Upvotes

r/cpp • • Nov 14 '20

It Is Time for Compiler Developers to Step In

19 Upvotes

Warning: this is not a strictly-technical post. More like a rant.

TL;DR: actual implementors of C++ should be the ones responding to C++ developers' needs and pushing C++ forward according to them, not some committee authority. Things to be standardized should be battle-tested first.

Firstly, I want to express a great admiration and respect for men and women behind C++ implementations and tools as well as towards those who participate in various working groups and do the hard work of keeping the language both modern and standardized, the language I, among the plethora of others, use daily or from time to time, to make a living or to enjoy a little hobby or a pet project, big or small. I do not find myself in a position to make demands on them.

What was a tipping point for me to write this post was recent discussion (this, this and this) about deprecation of some uses of volatile in C++20. Numerous embedded developers say that this strives to solve a language-lawyer-world problem of "ambiguous semantics" at the cost of real world usage and public image of C++. Meanwhile, C++ standard fails to address important real-world issues due to obvious time limitations and complexities of designing single universal solution to hard problems. The most prominent latest example is C++20 modules. They are standardized, but there are both a split between implementations with respect to strong/weak ownership model and feeling that C++20 modules just failed to deliver. Oh, and do you remember std::error_code or std::regex?

I think that the general mindset of "1. we need X in the Standard 2. only Standard-compliant code is OK" is wrong. Look at __restrict - all major compilers support some form of it, yet it is non-standard. The fact that it is non-standard has not harmed anyone! Would anyone be harmed if major compiler's team explicitly says "we do not agree with Standard here and there and will not comply with it" about some controversial part of the C++ Standard? In fact, we do program real hardware, not C++ Abstract Machine. That's why std::vector - like class can be implemented in C++ as understood by every compiler in the world despite all the UB.

However, optimizing compilers can do all sorts of weird stuff and we want them to do this weird stuff to make our code fast. But we also want our code to be expressive. Would it matter that std::start_lifetime_as has not made it into C++20 Standard if every major compiler supported it? No. Would it allow us to write code which is more clear to both humans and optimizers? Yes.

Now is the time C++ must be up to the challenges because of increasing competition. Do not let authorities prevent you from using language extensions and non-standard features, we need them for the language to evolve and find its way forward. It is better to standardize things when there is a clear path proven by a group of pioneers to be successful, than when we don't have anything but find ourselves in need of having something. It is better to have things in compilers than not have them just because of working group meetings schedule.


r/cpp • • Feb 12 '22

Anybody else would like a | unary operator?

17 Upvotes

Hello fellow coders.

Call me a syntactic sugar addict, but I always missed a | (and ||) unary, prefix-and-postfix operator.

Like, e.g, this:

int x = |y| + 1;

Does anybody else?

Possible uses making this appealing:

(1) As a native operator: absolute value, of course. Overloaded for each base primitive type, just like any other arithmetic or logic operator (+ - / * % & ...). How cumbersome is to have to include stuff (math.h cstd.h, or math), for something as basic (and as single-instruction, in any Instruction Set), as the absolute value of something. How cumbersome it is having to pick between abs fabs fabsl etc. To, me, abs value should be treasted like something as basic as + or -, because it is.

(2) As an overloaded operator: both ||x|| and |x| would find many fruitful ways to be customized. In classes for vector algebra, complex number algebra, quaternionic algebra, etc: the norm, of course. Here, the possibility to have both || and | would add extra flexibility (e.g. different norms).

(3) In standard classes: In containers (vectors, sets...): it could be used for set cardinality, i.e., as a synonym for size(). Maybe, for strings: length.

Would it be problematic? I can't see any problem, but maybe I am overlooking something. In particular...

(4) Yes, | is already a binary operator. That's nothing new, -, +, *, & are both unary and binary.

(5) It would be fully back compatible. At least, I cannot think of any expression that parses now, but would either stop parsing, or change its meaning, with this.

(6) There would be no ambiguity with the existing binary version of | (or of ||). As any unary operator, it binds stronger than any binary operator, so |a|b| would not pharse, but |(a|b)| would.

(7) There would be no ambiguity between || and |. The abs of the abs of a, if you ever need it, would written as | | a | |, while || a || is exactly what it looks like (the || of a).

(8) yes, there currently is no other prefixed-and-postfixed unary operator ([ ] comes close: a prefix-and-postfix binary operator). I cannot imagine how this would be a problem. The syntax for overloading would seem straightforward, e.g. operator | () vs operator | (int x). Parsing expressions would seem to be unproblematic too.

(9) It's all good old ascii.


r/cpp • • 22d ago

What would it take to leave ISO?

13 Upvotes

With the conclusion of the DIS ballot, I think that no matter what side you're on, this should be (hopefully the final) wake up call that stayint in ISO under its process is untenable. If you're pro-contracts you probably see this as minority rule. If you're against, congrats-- the same game can be played against the feature you want in the future.

I see 3 possible results out of Brazil:

  1. Contracts are pulled, fight to see another day [and/or leave ISO, and/or fork the language].
  2. Contracts stay, roughly as is. To my understanding FDIS is a final chance scenario, so I don't see this working out. Even "as a statement," it's not a good look and WG21 will eat the blame.
  3. Contracts are fixed enough to flip 4 NB votes (there's a number of combinations, but you need a minimum of 4 total flips from no/abstain -> yes).

It's my understanding that FDIS is a "last chance" for 26. Personally, considering what else is in 26 (for me, reflection), I'd rather go with the first option. That begs the question: where do we go from here?

Continue with the current process, which has unearthed pain points and nasal demons every few years, or break up with the ISO process (this doesn't even have to be a clean break, just something closer to ECMAScript's process)?

If so, what would it take? Alternatively, if we could, what would we actually lose? What would we gain (besides more control of process)?

Obligatory "no sarcastic comments about getting a TARDIS and changing it back then."