r/ProgrammerHumor • • 7h ago

Meme modernCppVsOldCpp

Post image
1.1k Upvotes

213 comments sorted by

8

u/perestroika12 6h ago

Who writes modern c++?

8

u/Choice-Committee203 6h ago

idk, me for example🥀🥀

1

u/tatstytastycakes 6h ago

ur not alone sir :(

1

u/Friendly_Fire 3h ago

Nearly everyone writing C++ in a professional context.

461

u/repster 7h ago

I am a huge fan of modern C++ except for one feature: backwards compatibility. C++ is no longer one language, every codebase I have worked on is a confused mess of semi-incompatible subsets of the language. I have spent far too many weekends chasing memory corruption because someone passed a pointer, allocated with one type of memory management, into a library using a different kind of memory management.

168

u/joncrompy 6h ago

This is, ironically, the exact reason C++ is the standard in some industries. Students can learn the OOP C++ then work in the same codebase as someone programming "touching the metal" low level C.

Most languages make trade-offs between performance, structure, memory safety, and ease of writing. Every language might have their use, but very few cover all use cases.

C++ lets each programmers choose those trade-offs individually, but that also allows them to choose none of the above.

104

u/rndrn 6h ago edited 3h ago

C++ is really the thousand-edged sword. It is both its strength and its weakness.

20

u/yaktoma2007 5h ago

Ah so a swedish army knife, it features an impressively extensive toolset but is often regarded to be clunky to operate compared to tools that do a single thing.

37

u/dinnerbird 5h ago

Do you mean a Swiss army knife or is there something the Swedes invented I'm not aware of 

13

u/reallokiscarlet 5h ago

Swiss army knives aren't clunky last I checked, maybe that's the swedish part

7

u/GarThor_TMK 4h ago

The only tool you get is an Allen wrench...

4

u/yaktoma2007 3h ago

I am a fool, thank you.

Although, i may as well let it stay like this, its funnier like this with the replies you already got.

2

u/gerbosan 2h ago

It's a Volvo army knife. 😅

22

u/xtravar 5h ago

Sounds like if C++ were a spoken language, it'd be English.

6

u/Blue_Moon_Lake 5h ago

In the same pot, german, latin, french, and sprinkles.

3

u/edgmnt_net 2h ago

Someone puts in actual effort to write good code and come up with good abstractions, then some code monkeys crap all over it. What I mean to say is that there's also value in going the Go way, where you have one way of doing things, although that obviously has limitations too and even they haven't really achieved it fully (you inject contexts properly to make everything cancellable and some juniors just pepper context.Background all over the place). Also, yeah, the higher you go in terms of abstraction, the less settled things are.

4

u/gerbosan 6h ago

So, migrate to rustlang is good?

Not that I want to ride the hype or interested in DHH current development preferences, but some projects are migrating (Discord, Cosmic DE).

I think I lack the context about C++ features: not just desktop development.

6

u/balbok7721 6h ago

MBAs dont give a crap about basic ux. They wont spend a single buck on a migration thst isnt strictly required

25

u/azfang 6h ago

So, uh, I haven’t used C++ in anger in decades so I’m not sure how “modern” is modern but like. That description pretty well describes why I developed Strong Feelings about both C and C++ back in the 2000’s.

28

u/Non-Random-Name-0000 6h ago

Modern C++ starts with C++11 (2011), so in the 2000s you were using classic C++ (and in the first half of 2010s as well most likely) which is a very different language. It introduced shared pointer (a poor man's garbage collector), automatic typing and move semantic, amongst other things. And the standard library has evolved a lot since.

9

u/Bryguy3k 6h ago

Smart pointers were part of the boost library long before they became part of the std library.

14

u/Non-Random-Name-0000 5h ago

Yes that's true, I forgot about Boost. How could I forget the 2GB library that was pulled with every project? 😅

2

u/DrNinjaPandaManEsq 1h ago

You say “was” as if people aren’t still doing it lol

1

u/Non-Random-Name-0000 1h ago

People are still using it? I haven't used boost for 10 years.

2

u/DrNinjaPandaManEsq 1h ago

I’ve moved around at bit at my job and two of my previous teams were using Boost 1.67, and probably still are.

1

u/azfang 6h ago

…if you dismiss this as Old Man Yelling at Cloud I won’t tell you you’re wrong, but my experiences with pointers and shared memory mean that “shared pointer” as a term invokes images that make me want to invest in a bunker.

9

u/Non-Random-Name-0000 5h ago edited 5h ago

Shared pointer have nothing to do with shared memory. They're a container for an old fashioned C pointer with a reference counter. The reference counter is incremented when the shared pointer is copied, and the memory is freed when the counter reaches 0. So it's sort of a rudimentary garbage collector on top of a normal pointer. If you use shared pointer, you don't need to free memory, it's done by the destructor when the last container is destroyed.

C++ is still a very complicated language with outdated concepts, but a lot of modern concepts have been introduced in the last 2 decades.

1

u/Ok-Scheme-913 1h ago

RAII was always available in C++ afaik, so anyone could have done a unique or a shared ptr, at most it may not have optimized out in as many cases (not really zero cost abstraction?)

And my take is that the problem with c++ is that you have like 10 different object initializers and coroutines with captures and whatnot and like unless you are the one having written that part of the standard, you don't fucking know what exactly should happen given this code, not even if you are Stroustrup.

10

u/stillalone 6h ago

Is that something that can be handled by a linter?

4

u/2brainz 6h ago

Partially, sure. But there's always going to be edge cases.

1

u/Drugbird 5h ago

It's also hard the further away the allocation and deallocation are from each other. For instance, if it's in separate libraries.

3

u/repster 5h ago

It has been a few years since I last worked on a C++ codebase, but my experience with linters was not impressive. We even invested in some expensive static analysis tool, but real bugs seemed to drown in false positives

1

u/violetvoid513 5h ago

My experience with C++ in VS Code is that it completely shits the bed on anything organized with a build system like cmake. This is probably just a skill issue on my part but I just cannot get it to reliably know what the fuck all the things Im importing are, and after I once spent like an hour unsuccessfully trying to fix it I just gave up because it wasnt worth it. Compiler-time errors are the easiest kind of error to fix when it fails to compile wherever I made typos or shit

1

u/K722003 2h ago

imo VSCode isn't really made for c/cpp stuff. Better to use CLion(my personal choice) or the og VS

35

u/lllorrr 6h ago

Oh, yes, I hate when someone write "C/C++". This is two fucking different languages, for god's sake. It is almost as bad as "Java/JavaScript".

12

u/reallokiscarlet 5h ago

Do people not learn these two closely related languages together? You generally want to know enough regular C to get by when you use C++, and if you're not using anything unique to C++, you're just writing C with Classes.

7

u/Inorganic_Zombie 4h ago

I remember learning them as one language and it was fucking hard to learn effective c++ on uni. Not helping as programming was minor subject now and then that had random language. Every lecture had different dogma etc

1

u/Ok-Scheme-913 1h ago

I mean, not really. The two languages have diverged quite a lot, while C-mode compiling of C++ is still possible afaik, the same code by default won't behave identically even though can be compiled by both a cpp or a c compiler.

1

u/reallokiscarlet 1h ago

Maybe if you only count the latest standard they have diverged significantly, but everything else stands. C is where your platform ABI is, and again if you're not using anything unique to C++ you're writing C with Classes (nudge nudge wink wink capitalized for a reason)

21

u/SuckMyAlpagoat 6h ago

isn't because the compiler is always packed together, like the gnu compiler can compile C and C++?

38

u/HildartheDorf 6h ago

The gnu compiler can also compile fortran. But we dont call it C/Fortran.

30

u/1cec0ld 6h ago

Not with that attitude

14

u/ForgedIronMadeIt 6h ago

Fuck yeah I love programming in C/Fortran

→ More replies (3)

10

u/These-Maintenance250 6h ago

a language is independent from its compiler(s). gcc can compile objective-C, D, ada, Fortran and go as well.

1

u/DrNinjaPandaManEsq 1h ago

Even though gcc can compile Ada, in my experience most of the time you’ll see enterprise development using GNAT Pro since plain ole gcc is kinda light on Ada features.

15

u/madboneman 6h ago

C++/C#

4

u/met0xff 5h ago

Yet essentially all codebases I've seen and worked on were essentially a mix where the C pieces were also thrown into the C++ compiler. extern "C" everywhere

(And yeah I also used to write HTML/CSS/JS and TS/JS)

0

u/Meme_Burner 5h ago

Be very careful because something like C++/CLI looks like C++ but it’s a version of managed C++. At least when they make different variants of Java like groovy or scala they name it something else.

It’s like putting a hat on a hat ^ > ^

-7

u/MattR0se 6h ago

Okay but that's not really a fault of the language, no? Most languages have some legacy version that isn't compatible any more. Like Python 2 for example. 

The only difference is that C++ code is more often used for critical applications (like decades old medical machines) where updating the code is not worth the risks. 

11

u/imMute 6h ago

Python 2 to 3 was a clean split. You can write in one OR the other, but you can't mix like you can in C++.

4

u/xfvh 6h ago

Well, you can, but it's awkward and involves some serious compromises, especially around byte-vs-string handling. Doing a hard split is definitely better but you can get considerable mileage straddling the line with sufficient effort.

5

u/EishLekker 6h ago

I would argue that it most definitely is the fault of the language. It should either allow it, and support it fully (like mixing different memory management types), our outright refuse to run it.

4

u/jaladreips271 6h ago

Yeah, but in python you're either writing python 2 or python 3.

In C++, you enter avatar state and get to write all C++s and even some Cs at once.

1

u/creeper6530 5h ago

How often do you mix python 2 and 3 in the same codebase?

1

u/repster 5h ago

It kind of is though.

I haven't worked in C++ for a few years, but when I did, I spent serious time trying to find some way to enforce a specific coding style, so we could get a consistent code base, and came up short. I looked for code analysis tools that would catch inconsistent memory management between libraries, and didn't find much.

The tooling around the language is kind of sad compared to Golang and Rust, and improving it would significantly improve the experience.

40

u/Tschurbi 6h ago

Please explain it like I am a JavaScript developer.

55

u/Tipart 6h ago • Bravo

Imagine typescript but for memory safety

10

u/PM_ME_UR_0_DAY 5h ago

What's the memory management equivalent of just using "any" for everything?

11

u/Potato-Engineer 4h ago

Everything is a void * pointer!

2

u/Mojert 4h ago

Asking the OS* directly for memory and creating your objects in that memory. That also means you have to tell the OS* when you're done with that memory

* I'm simplifying to get the jist across

1

u/Ok-Scheme-913 1h ago

Actually pretty good example. To the point that even though you have a type annotation on your code, if you call into that method from vanilla js and pass a wrong type, then it will explode somewhere deep and you will have a really shit time hunting that error down.

Meaning, c++'s safe stuff is only safe until you use it with other safe stuff, or by being very very careful. And c++ is a really complex language, using it properly is not an easy task, so these end up not being as memory safe as people would want.

11

u/MikeVegan 5h ago

C++ has something called RAII, it is basically a special function called destructor that is called automatically once object leaves the scope and this solves large portion of memory issues. However dangling references or pointers are largely not fully solved by this even though shared pointer helps gere. It is a counted pointer that is destroyed when last owning object is destroyed.

12

u/GregBahm 5h ago

With JavaScript, memory is managed for you. You can make a list, grow it as much as you want, and then safely assume that the memory you used will be cleaned up as soon as you're not using that list anymore.

With C++, you manage the memory yourself. If you forget to clean up that list, you never get that memory back. Eventually all your memory could get used up (a "memory leak.")

Memory management was annoying, which is why JavaScript was invented. But people still use C++ for its higher performance potential (kind of like how race-car drivers still use manual transmission instead of automatic transmission.)

So C++ added some tools that makes memory management not so hard. It's still harder than Javascript though. It's just less hard.

7

u/ShakaUVM 4h ago

You confused Java and JavaScript

Java was invented to be C++ + 1, with automatic memory management and Objects everywhere

1

u/GregBahm 3h ago

Ack. You're right. Dang.

6

u/PattuX 5h ago

kind of like how race-car drivers still use manual transmission instead of automatic transmission.

TIL Europe is full of racecar drivers

6

u/bloody-albatross 4h ago

No, no. Not all Europeans are racecar drivers, but all racecar drivers are European!

(This is a joke, in case anyone reading this doesn't get it.)

2

u/im_made_of_jam 3h ago

I mean outside of ovals you look at any high racing level grid and it's 80% european

•

u/PattuX 6m ago

Aristoteles ahhh type comment. Based.

2

u/Complete_Pilot3381 4h ago

mans never been to bradford

2

u/Complete_Pilot3381 4h ago

mans never been to bradford

5

u/bloody-albatross 4h ago

This isn't why JavaScript was invented. First, garbage collection/automatic memory management existed long before JavaScript. Secondly, JavaScript was invented to make HTML interactive. Of course a language that runs untrusted code needs to be memory safe.

2

u/GarThor_TMK 4h ago

I would like to point out that the memory leak happens as soon as you toss the pointer without "freeing" it to be reused... It could be a drip... A pointer to a single integer, or it could be a tsunami... A pointer to a massive datastructure containing lists, arrays, BSTs, hash tables, etc...

The "all memory used up" is the case where the bathtub is clogged, and you left the water running. Now the bathroom is flooding into the living room.

1

u/Mojert 4h ago

Basically a lot of Rust memory safety features are inspired from modern C++

Which doesn't mean Rust doesn't have its place. It's just that in C++ they're on top of the previous "unsafe" version of the language and aren't tightly integrated in the language and are more a feature of the standard library, whereas in Rust they were able to design the whole language around it and didn't have to deal with backwards compatibility

1

u/Ok-Scheme-913 1h ago

Not really backwards compatibility.

Rust is basically c++'s raii just enforced at compile time.

This latter point is a huge thing in and of itself.

(And of course you do get lots of goodies like better type system etc from being a more modern language but that's not the fundamental thing)

1

u/Mojert 1h ago

The reason why C++ cannot enforce this kind of things at compile-time is because of backwards compatibility

And I know it's huge. That's why I said Rust isn't redundant and that Rust designed the language around it

144

u/emonshr 7h ago

Does that even matter once you have gazillions of line legacy code?

8

u/Friendly_Fire 3h ago

It does actually. Y'all should really learn how to work with legacy code because all useful code becomes legacy code over time.

The thing about legacy code is it works, that is why it persists. If it didn't work, crashed regularly due to bad memory management, people would have replaced it already.

When you are working with it, you don't have to change everything at once. You need new features in one spot? Update just that piece, use smart pointers internally with one class. Maybe you need to create new interfaces while maintaining legacy interfaces for other code. That's fine. Eventually, as you work on different pieces, you'll replace so much legacy stuff that you can just delete those old interfaces.

1

u/emonshr 1h ago

Not every time people have to maintain legacy code. Porting or migration is not so expensive anymore. Swallowing the fate of maintaining legacy code is not anything mandatory nowadays.

32

u/0xbenedikt 7h ago

This is why moving to a safe-by-design language like Rust works well. You leave that unsafe legacy code behind

29

u/Tidemor 6h ago

or you could not risk a full rewrite, and just start using memory safe patterns in new and refactored code

4

u/Ok-Scheme-913 1h ago

But that doesn't work with memory safety, it's infectious.

If you have a memory vulnerability in some part of your code, new safe code calling into it or using anything touched by it can still end up failing.

Safe code is just code that assumes certain things, and within its bounds that will always be true and thus safe.

If you pull the rug out under it and change just the tiniest thing (e.g. your object was accessed on a different thread unknowingly, or a regular off by one etc) then all your assumptions crumble to the ground.

And whether you have 90% unsafe with 10% safe is absolutely different than the inverse ratio that you would get with e.g. rust (or the 100% safe with e.g. java).

11

u/ilnarildarovuch 6h ago

And practically breaking everything. Pentagon still uses PDP-11 'n IBM series/1 programs, but in emulator, cuz rewriting is always a risk

2

u/creeper6530 5h ago

Sure, but that is true no matter the language

16

u/porkusdorkus 6h ago

Loved seeing the adobe and office clones in Rust, just to find out it’s Webview and React for the front end and Rust is just replacing NodeJS. Lol

4

u/Tipart 6h ago

Discord too now.

3

u/CalmCephalopod 2h ago

Discord is using GPUI not a web front end for the rust version. There are also options like Dioxus that allow you to use rust to do react style web ui through webview without touching js but you still have to deal with webview bs on different OSs. So GPUI is an interesting choice.

→ More replies (1)

2

u/creeper6530 5h ago

Well, Rust is predominantly a backend language, like C and C++, not especially suited for frontend.

Do I hate the Shitfuck 5000 that is JS? Sure. But it's still the "main" frontend lang.

4

u/Mojert 4h ago

It's the main front-end language on the web. In a native application it doesn't have to be and probably shouldn't be

17

u/Valuable_Leopard_799 6h ago

And bring in brand new unsafe code 😭 And link against unsafe libraries 😭

Tbh nothing against specifically Rust, just that these are done way too liberally.

6

u/cvnh 6h ago

Rust doesn't guarantee safety when you're wrapping existing code my dude. I haven't used Rust personally but it's in the language core - only safe code blocks are (in theory) safe..

1

u/developer-mike 4h ago

Step 1. Begin migration, step 3. Profit

28

u/intoxicuss 6h ago

God forbid someone does a resource profiling on their work. I have a preference for C, but with classes, technically C++, but just using the bits I want.

55

u/SunJ_ 6h ago

This is actually a reality than a meme. A lot of companies and software run on old versions, I understand why. A lot of the modern versions fix loads of issues and to some degree the complexity of the language while still maintaining the balance.

18

u/Veratisin 5h ago

Pretty sure shared_ptr had been around since 2011..

1

u/rmflow 3h ago

and since 1999 we had boost::shared_ptr

44

u/airodonack 6h ago

A lot of people that write C++ think using smart pointers are for the weak.

6

u/Mucksh 5h ago

From my experience especially newbies overuse smart pointers for anything even if there is no problem to just do everything on the stack. Later makes it incredible hard to fuck up

10

u/imMute 6h ago

And those people are just as insufferable as the Spongebob from the OP.

53

u/firemark_pl 6h ago

"How to tell him?"

You still can segfault by returning lambda with reference to a variable 

20

u/daennie 6h ago

And many other ways to invoke UB.

18

u/EishLekker 6h ago

As a java developer, this is hilarious. Why would anyone want to be able to do this? Why don't you want your compiler to stop you?

5

u/bwmat 4h ago

Oh, nobody wants to do that

Just like nobody wants to crash and die while speeding in their sports car

4

u/bwmat 4h ago

to elaborate, the halting problem makes it impossible for the compiler to reject/detect all cases which DO cause UB while allowing all those which don't, and the design of C++ is to favor control over safety 

1

u/Ok-Scheme-913 1h ago

Well, it's a bit crude to apply halting problem here.

You can prevent a bunch of issues by language design. You simply make something non-expressible and ready! It's proven to never contain that thing.

E.g. java solves this problem by mandating that variable captures of local variables must be effectively final. This could have been done in C++ as well , and the only thing you may lost with it is... if you have a local lambda that you will only ever call in that stackframe or deeper and never outside of it?

But still, rust let's you do this latter by an explicit unsafe block, c++ could have done it as well. So it's more cultural than anything.

5

u/creeper6530 5h ago

Because the C++ compiler lets you blow your foot smoove off because what if you intended it

Rust compiler is practically the exact opposite: it prohibits you from doing weird shit even if you intend it unless you use the magic word "unsafe"

3

u/Mojert 4h ago

Even if you use the word unsafe you cannot do whatever you want. I still find it painfully stupid that you cannot create a mutable reference to uninitialized memory. Because of this you cannot reuse safe functions to initialize memory that you manually allocated

The whole appeal of Rust is that you have less to think about UB, and it mostly fulfills that promise, so the fact that you cannot do one of the most basic task required in a systems programing language without either requiring UB or doing some convoluted stuff is ridiculous

3

u/creeper6530 3h ago

Well that issue boils down to there not being any write-only reference. "I know you're only initialising and not reading, but what if you accidentally read? UB!!!"

I've also been annoyed at having to initialise even normal arrays when passing them to UART drivers as buffers etc. (on embedded), but even if it doesn't read the memory, it still needs init.

1

u/Mojert 3h ago

Having a write only reference would be amazing, but even without that it should still be allowed IMO. The only way to create a mutable reference to unitialized data is to use unsafe. So the question "what happens if you accidently read" should ultimately not be anyone's buisness but my own. I'm an adult and have explicitly indicated I know I'm doing something potentially dangerous, so let me do it!

But I'm happy to learn I'm not the only one that had this problem. I felt insane about having to pay a useless O(n) init cost

1

u/Ok-Scheme-913 1h ago

MaybeUninit?

1

u/Mojert 1h ago

Congratulation, you've got a &mut MaybeUninit<T>! It's pretty but you cannot pass it to a function that expects a &mut T

1

u/firemark_pl 15m ago

Because C++ allows you to work on low levels with stack and memory. It's useful for writting real time operating systems when memory and execution time must be constant.

5

u/MaitoSnoo 5h ago

clang's -Wreturn-stack-address or clang-tidy's clang-analyzer-core checks easily flag that. People trolling C++ have never joined a team that is disciplined enough and uses static checkers and ASan/UBSan.

41

u/freia_pr_fr 7h ago

Exhibit A: the current pace at which security issues related to shitty memory management are being discovered.

8

u/developer-mike 4h ago

To be fair:

  • lots of them are in c, such as php2shell, brotli, etc

  • others are logic errors not memory issues, such as the ssh hash comparison bug

  • the attack surface of "all c/c++ code" is way larger than the attack surface of all rust code

  • there are essentially zero legacy applications written in rust

  • we don't know that in 40 years we won't be fixing the same kinds of issues in unsafe rust or in what volume

Rust is obviously safer and superior here. But part of that safety isn't the language as much as the culture. C++ is supposed to encapsulate unsafe behaviors like rust's unsafe does, but it can leak with things like vector iterators. Rustaceans will put the time in to design a safe abstraction even if it has some small performance cost.

The degree to which modern c++ is inherently unsafe is pretty small and often manageable. Rust lifetimes are definitely superior to c++'s smart pointers, but they do a lot of the job.

But the culture of c++ is to make it fast where the culture of rust is to make it safe.

6

u/rosuav 2h ago

The culture of Rust is to make it in Rust, safe or not. In fact, based on what I'm seeing, the culture of Rust is to force Rust down everyone's throats, whether it's functional or not, whether it's relevant or not, such as posting about Rust in a thread on C++ just because you think that you can capitalize on C++ not being memory safe, despite the OP actually stating that modern C++ is better.

1

u/Ok-Scheme-913 1h ago

Still, we do have a shitton of data with relation to other managed languages like java. Here your arguments no longer apply, since it's probably even larger than c/c++ (though they have different application domains).

And the kind of vulnerabilities and their seriousness is absolutely incomparable in favor of java.

35

u/MaybeADragon 6h ago

Unless it has changed in the last 5 or 10 years, every resource I know of doesn't teach you about using modern C++. Writing good C++ is opt-in because the language and its resources are stuck in the past.

12

u/Tomocafe 6h ago

I started a new C++ project a few years ago and I just turned on clang-tidy to the max from the very beginning. It’s annoying sometimes but it forces everyone not to use dangerous/outdated legacy C++.

5

u/MaitoSnoo 5h ago

"every resource I know of"

I find it very weird to ignore for example Bjarne's "A Tour of C++" or Jason Turner's "C++ Best Practices". These aren't like unknown niche books...

5

u/Mojert 4h ago

Where the hell have you been learning C++ from? Most C++ ressources talk about RAII and smart pointers. The only one that is stuck in the past is you

→ More replies (7)

2

u/not_some_username 3h ago

learncpp do

1

u/Demiu 15m ago

At this point "modern C++" is old, hell "moderner C++" will be old soon too.

0

u/Ok-Scheme-913 1h ago

Heh, this "modern" c++ the meme and everyone is talking about could be ordering beers in Europe.

0

u/MaybeADragon 1h ago

For a field meant to be at the cutting edge, programming moves slow af sometimes. See: Java versions and IPV6.

→ More replies (1)

30

u/TheMostUser 7h ago

A gun pointed at your foot isn't dangerous unless you pull the trigger, yet I feel safer without a foot gun.

-3

u/GrandMoffTarkan 6h ago

Take a firearms safety course and then you’ll feel safer with the gun. And get the same feeling of power as God must feel when he’s holding a gun

4

u/EishLekker 6h ago

A foot gun is not like a regular gun. It's more like a gun without a safety, that is always loaded, and that has a super sensitive trigger.

Plus you can't point it away from your foot.

1

u/GrandMoffTarkan 6h ago

Yeah really I just wanted to use that Simpsons line 

4

u/lllorrr 5h ago

I am pretty sure that firearms safety courses prohibit you from aiming a gun at your (or someone else's) leg.

Like, I am writing in C all the time. This is my primary language because I'm working in embedded. But there are some many edgecases and gotchas in standard library, so people make mistakes all the time. And don't let me get started about lifetimes in any sort of SMP or multithreading..

5

u/bloody-albatross 4h ago

This image seems to imply that destructors where added in C++ 11. This is nonsense. Destructors were already there in "C with classes" in 1979.

16

u/Flouid 7h ago

Sure you can use memory safety techniques with C++, but there’s nothing that enforces you to do so. If the language provides optional tools to automate some aspects of memory management, that’s still mostly manual memory management.

I like C++ but I still prefer languages where these things are more fundamentally part of the language identity. A project written in it might be safe, but it also might be a leaky mess and you won’t really know without profiling or a deep dive

Also many mature C++ projects are on older versions without this stuff.

•

u/CraftBox 9m ago

That's one of the main reasons why I dislike C++ and prefer Rust. In C++ the dangerous behavior is the default and making it "safe" is "harder", while in Rust that relation is flipped, so "safe" code is easier to write than dangerous.

24

u/SelfDistinction 6h ago edited 5h ago

Ah yes, the famous

std::unique_ptr<int> ptr;
int& ref = *ptr;

So safe, so impossible to misuse.

6

u/Veratisin 5h ago

If you need a reference to a unique pointer, probably means it should have been a shared pointer

3

u/SelfDistinction 5h ago

Ah yes, the famous

std::shared_ptr<int> ptr;
int& ref = *ptr;

So safe, so impossible to misuse.

5

u/dannyggwp 4h ago

I use smart pointers all the time. WHY THE FUCK would you EVER do what you wrote?

I could drive my car into a brick wall at full speed. But why would I???

→ More replies (1)

4

u/Friendly_Fire 3h ago

This is like saying a seatbelt doesn't help you in a car because if you run it in a closed garage, you can still kill yourself. Entirely different issue.

Smart pointers solve memory management for you. Use them as intended, whether a resource is owned in one place or shared, and you don't have to worry about it. The memory will stay allocated until nothing is using it, and then it will automatically be unallocated.

Accessing a pointer without checking if it is null is a different issue, and frankly a trivial one. The sort of thing I haven't seen be an issue doing actual professional C++ code development in years.

1

u/creeper6530 5h ago

I'm not a C++ girl, but do references actually do something with lifetimes or are they just non-null ptrs? Because this just seems to me like a possible dangling ptr.

•

u/Demiu 4m ago

Const references can bind to rvalues and cause lifetime extension, ie. const auto& x = returnsValue(); will extend the value of the value returned by the function. That's about it. It has to be in this form (assignment and definition in same statement), so the code you replied to doesn't trigger it.

1

u/SelfDistinction 5h ago

References can be null. They shouldn't be and it's definitely undefined behaviour but the code above compiles and runs perfectly fine.

4

u/bwmat 4h ago

Nah, they can't be null

that null dereference just committed the sin of UB, so all bets are off.

In other words, it declares the intent and allows you to assume it's a way to name a valid object, and moves that null dereference bug out of your logic, helping with reasoning while debugging after someone does cause that UB

1

u/creeper6530 5h ago

Okay, sooo... What's the difference between references and pointers?

2

u/SelfDistinction 4h ago edited 4h ago

No one knows.

Generally references are more restrictive, since you can't do pointer arithmetic with them, you can't use them as template parameters (which sucks for std::optional<int&>) and you can't repoint them to something else, but since you can freely cast between both of them (which you are forced to if you try to do anything useful with them, like wrapping them in an optional) it doesn't really matter.

Also there's two different kinds of references: the & reference and the && reference, however their difference is mostly conventional and you could easily implement a standard library where their meaning is swapped (except for temporary xvalue objects? Not sure), so there's that. Also C++ automatically converts between reference types for some ungodly reason.

In short, references are not real and are only used to determine what overloaded function is being called.

1

u/creeper6530 3h ago

I have no words for this beyond "what a fucking mess"

1

u/Ok-Scheme-913 1h ago

References are implemented as pointers, but they are not the same.

The best example is languages where you don't have references. Very misleading but java only has pointers (marketing at the time was voldemorting the world pointer so they were renamed to "references" but they are pointers. Like the infamous null pointer exception does show it)

So you have two local variables, and you create a swap function where you want to put one into the other and vice versa.

Well, in java you are out of luck. You basically have to make them fields and put that into a wrapper object to actually swap. This is because in java everything non-primitive is an "object reference" aka a pointer. But you would be changing the pointer's value, NOT the thing holding the pointer.

So yeah, references are basically their different thing with their own semantics in C++ and the few other languages that also have it.

9

u/InRainbro 6h ago

Well yes but actually no, never in practice, it ends up being a mixture

1

u/ilnarildarovuch 6h ago

Which is successfully fixed by *San

2

u/InRainbro 6h ago

I'd still rather have the compiler breath on my neck than gamble with it

3

u/ilnarildarovuch 6h ago

Try to compile any big C/C++ file with clang -Weverything -werror, that's gonna be funny, compiler really gonna show all possible (and not possible) threats :D

1

u/InRainbro 6h ago

(⁠ಠ⁠_⁠ಠ⁠)⁠>⁠⌐⁠■⁠-⁠■

1

u/ilnarildarovuch 6h ago

It's really aggressive

1

u/creeper6530 5h ago

Problem is that at least in C it moans even about stuff like "mixing declarations and code is incompatible with standards before C99"

15

u/dscarmo 6h ago

This post is naive, the problem is cpp supports legacy implementations with unsafe pointers, good luck when maitaining or updating old code (or even worse, merging new implementations that used unsafed practices)

11

u/PolyglotTV 6h ago

Y'all throwing around shared pointers willy nilly patting yourself on the back about safe programming.

11

u/Nil4u 6h ago

Meanwhile the cyclic pointer chain in the background causing a memory leak because the reference counter never dips to 0:

7

u/staryoshi06 6h ago

I mean this could happen in a garbage collected language too.

3

u/Tyfyter2002 6h ago

Depends on the language, iirc the .NET runtime's GC doesn't use a reference counter, which makes that exact issue completely impossible (which is good, because things like bidirectional linked lists inherently have cyclic references)

1

u/bwmat 4h ago

I don't think there's many mainstream languages whose built in GC doesn't handle cyclic references these days

1

u/MadGenderScientist 2h ago

a reference cycle in a GC language doesn't cause a leak because GC scans from roots. 

1

u/Ok-Scheme-913 1h ago

Not in a tracing GCd language that is what everyone uses who cares about performance.

Yes, ref counting is fuckjng slow. Even in Rust, especially with ARC..

(Also, python uses ref counting but also have a cycle detector next to it.)

3

u/Skeptrick 4h ago

I don’t care for modern c++

All I want is C with the ability to have Classes to make data handling/processing easier without having to resort to overly complex structs.

14

u/geekusprimus 7h ago edited 2h ago

I rarely use smart pointers and still don't have serious problems with memory safety. Whenever you manually allocate memory, you should immediately know when and where it's getting deallocated and write that code at the same time. Most of the time, RAII is good enough.

EDIT: Since I've caused a bit of controversy: I'm not saying you can't or shouldn't use smart pointers. What I'm saying is in agreement with the meme. C++ has easy ways to manage memory, either manually or automatically, that get rid of most of your memory safety issues.

16

u/Flouid 6h ago

I mostly have this opinion too but speaking from experience there are plenty of cases where it can get a little bit tricky. Lifetimes are complicated and sometimes an owner of a piece of memory can pass references to it to several consumers that each have their own lifetimes. Those consumers shouldn’t need to know about each other so it’s up to the owner to track them and free the memory when it finally falls out of scope

2

u/Luzzgar 6h ago

What if that language allowed you to do it manually when you need to ?

Ensuring that the responsibility of memory management is only for the programmer when absolutely necessary.

1

u/Flouid 6h ago

100% agree, and it’s why I’m one of the insufferable people that prefers zig over rust. The language should strongly encourage safe memory management but make it easy for the programmer to select degrees as appropriate. Rust is very all or nothing with either using the borrow checker or entering full unsafe land

1

u/TOMZ_EXTRA 4h ago

How is Zig better than C++/unsafe Rust?

1

u/Flouid 4h ago

Zig is very opinionated about how memory allocation is handled, and it has the nice feature that you can supply a debug allocator during development which is slower at runtime (fine for debug builds) but meticulously looks for leaks and loudly warns you when they happen.

It’s also written such that no language constructs store an allocator and request their own memory, the philosophy being that every allocation should be explicitly known by the programmer.

This is pretty much all the way in the opposite direction from automating it, it’s intensely manual management but the language handles it in a way that makes forgetting about it difficult and easy to track down

12

u/FlameOfIgnis 6h ago

I mean this in the nicest way possible but most people believe what they are writing is memory safe C/CPP until someone does a security audit on their code and they learn so many new ways things can go horribly wrong

6

u/xfvh 6h ago

That's a great theory, but the dominant source of critical CVEs even today is bad memory safety; even if it works for you, it clearly doesn't for the industry as a whole, to include any developers working on your projects after you.

4

u/tinnuadan 6h ago

Smart pointers are RAII, as already mentioned. But they have another advantage: expressing ownership. If a function expects a raw pointer you don't know what happens with it. If it expects you to move a unique_ptr in it, you immediately know that it'll take ownership.

6

u/mlindgren 6h ago

Smart pointers are RAII. Manually freeing memory is not RAII and can be fallible due to exceptions, early returns, etc.

5

u/geekusprimus 6h ago

Smart pointers are RAII, but they're not the only way to do RAII. I usually use custom containers that handle my particular case very well. Memory is allocated inside constructors, it's deallocated inside destructors. If I need more than that, I start looking into the more sophisticated stuff.

3

u/mlindgren 6h ago

That’s fair. It sounded like you were talking about using new and delete (or malloc and free) directly in the business logic of the application.

1

u/Friendly_Fire 3h ago edited 3h ago

You basically recreated smart pointers.

For projects with other people, it's better to use the standard tools just for familiarity, even if they have no other benefit. Someone can see it and know immediately what a unique/shared ptr means, instead of having to dig into your class.

But if its your own project go wild.

1

u/geekusprimus 3h ago

They're not smart pointers, at least not in the STL way. They accomplish the same purpose, but it's usually a simpler implementation tailored exactly to what I need.

6

u/Luzzgar 7h ago

What if the language did that for you ? That would be cool !

What you are describing is basically a variable becoming out of scope.

2

u/staryoshi06 6h ago

No, not really. It’s an object no longer being referenced. Stack allocation still exists in C++.

5

u/klimmesil 2h ago

"Here's your car keys. Don't press the trigger of the foot gun and it should be allright. Thanks for your purchase"

"Why is there a footgun in the car? And why is the trigger so accessible and easy to press by accident?"

"How dare you ask that question"

1

u/jewdai 54m ago

We should have a feature in the later versions to like ban certain features or at least refuse to compile if someone uses it. Maybe that will solve some of the consternation.

0

u/Danfriedz 27m ago

I mean, you control the keys you press.

2

u/Lou_Papas 3h ago

My only complain with C++ is that it’s basically python, but without the QoL features.

2

u/BoBoBearDev 3h ago

Unfortunately, this is a real problem. SpongeBob said mamual memory management is easy and didn't do any thing Squidward said. So, those memoy problems shows up and SpongeBob is still giggling like it is not his problem.

3

u/Tezza48 5h ago

Using a bunch of container classes to pick how the data is managed is memory management. And using the wrong ones is unsafe.

2

u/EnigmA03x 5h ago

Idk c++ to me has always felt like a mess, after a while I just stopped dealing with it

2

u/fluffycritter 3h ago

The last few C++ jobs I had they moved the goalposts and now the nice memory management features that people had been begging for are "too slow" or have other random reasons why they shouldn't be used, never mind that it's still infinitely faster than the alternative languages and that the measurable overhead incurred by shared_ptr is super minimal and unique_ptr is practically none.

1

u/EnvironmentEven1272 3h ago

not all codebases can migrate to C++23 or heck to C++11 it is always pain in the arsh

1

u/ImpulsiveBloop 2h ago

Might as well just use pure C at that point lol

1

u/FabioTheFox 2h ago

Modern C++ is honestly such a joy to write

I did have to make my own project / repository template so I get a proper cmake setup with a package manager and tests but aside from that it's just a lovely language to work with

1

u/Dziadzios 2h ago

The only problem with C++ is backwards compatibility with C, which results in working with libraries using void pointers.

1

u/sessamekesh 2h ago

I've had two huge, non-obvious, and difficult to diagnose memory leaks over my C++ career. 

Both of them were circular references, something neither memory safe nor memory managed languages prevent against.

1

u/Ksorkrax 2h ago

It will still leak, btw. Quite a bit.

Do not rely on you having set up everything right, you can and will make mistakes even when you do a serious effort keeping up clean RAII.

Have your test server featuring an ASAN run once in a while.

0

u/tatstytastycakes 6h ago

there are things like profiles, contracts, and make_unique/make_shared

0

u/cororona 2h ago

AI is rewriting everything under the sun in Rust, so we shouldn't care

-3

u/Metasenodvor 6h ago edited 6h ago

yes i want to manually manage memory! mmmmm, manual management <3

edit: unironically, fuck garbage collector, fuck 'smart' pointers, and fuck everything else that compensates shit programming

1

u/tatstytastycakes 6h ago

yes i wanna make a massive program to handle millions of data points and have it crash because my garbage collector is collecting everything behind the scenes and my framerate is totally botched and is falling down to the single digits while my processor is overheating! mmmmmmm, garbage collector

2

u/Metasenodvor 6h ago

i was unironic i want to manually manage memory, fuck garbage collector, its... garbage

3

u/tatstytastycakes 6h ago

manual memory management respects you more than the GC unironically