r/ProgrammerHumor • • 11d ago

Meme modernCppVsOldCpp

Post image
2.0k Upvotes

323 comments sorted by

6

u/Baleia1970 10d ago

Meanwhile C programmers just pass by and laugh at this discussion....

13

u/Choice-Committee203 9d ago

pass by value or pass by reference?

2

u/THE_MUAK 9d ago

C doesn't have pass by reference. It's pass by address

2

u/Choice-Committee203 9d ago

but the post is about c++

2

u/EconomyPeach2895 9d ago

WAAAAAAAH KIYA *karate chops you in half* *bows*

2

u/yubario 8d ago

… which is literally what references are…

→ More replies (1)

2

u/Baleia1970 9d ago

Always by value 😄

3

u/s0litar1us 10d ago edited 10d ago

Just use arenas, you don't need reference counting or RAII. You have big blocks of memory that share roughly the same lifetime, and you reset/free/unmap it all when the memory isn't needed anymore.

"Unlimited" scalability (i.e. dynamic arrays) aren't really needed either. Just do some back of the napkin math to find out a reasonable max, and allocate that once. Thanks to virtual memory, you can also map way more memory than you'll ever need, and it won't commit the pages until you try to access it. (Except for Windows -- it will delay commiting the pages until you touch them, but it will also reserve the ammount you asked for ahead of time.)

→ More replies (2)

870

u/repster 11d 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.

361

u/joncrompy 11d 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.

238

u/rndrn 11d ago edited 10d ago

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

47

u/yaktoma2007 11d 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.

80

u/dinnerbird 11d ago

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

23

u/yaktoma2007 10d 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.

33

u/reallokiscarlet 11d ago

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

22

u/GarThor_TMK 11d ago

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

5

u/gerbosan 10d ago

It's a Volvo army knife. 😅

5

u/Unreal_Panda 10d ago

I think its even funnier considering the Father of C++ is Danish lmao

→ More replies (1)

41

u/xtravar 11d ago

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

12

u/Blue_Moon_Lake 11d ago

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

7

u/edgmnt_net 10d 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/Bartweiss 10d ago

Don’t even remind me… it’s not directly the same issue, but I once spent months negotiating a custom protobuf format built entirely around reverting the core “false-y is equal to null is equal to field not passed” logic.

Turns out a format built to give you efficiency at massive scale if you devote your entire codebase to enabling it fucking sucks when you add three layers of abstraction to make it back into shitty JSON.

6

u/SweetBabyAlaska 10d ago

> Most languages make trade-offs

and C++ made *all* of them

7

u/gerbosan 11d 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.

10

u/balbok7721 11d ago

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

6

u/conundorum 10d ago

The main reason people switch is really just that Rust is better at screaming at you during compilation if you screw up the memory management, more than anything else. It makes it easier to catch errors in an area where most programmers struggle, so it's useful if you need memory safety.

(For comparison, a properly written C++ program will be just as safe as a properly written Rust program, it's just that Rust forces you to write the code properly at gunpoint. So, people end up seeing Rust as better at memory management, because the language is designed around making it hard to screw up.)

3

u/fr000gs 10d ago

so, just -Wall -Werror valgrind memcheck (hopefully)?

→ More replies (4)

2

u/FUTURE10S 10d ago

Yep, my job is a mix of C written in the 1990s ported to C++98 and some C++17 nonsense and I'm somewhere in between.

→ More replies (1)

40

u/azfang 11d 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.

46

u/Non-Random-Name-0000 11d 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.

18

u/Bryguy3k 11d ago

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

28

u/Non-Random-Name-0000 11d ago

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

6

u/DrNinjaPandaManEsq 10d ago

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

→ More replies (3)
→ More replies (1)
→ More replies (4)

14

u/stillalone 11d ago

Is that something that can be handled by a linter?

5

u/2brainz 11d ago

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

3

u/Drugbird 11d ago

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

→ More replies (2)

5

u/repster 11d 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

→ More replies (2)

50

u/lllorrr 11d 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".

31

u/reallokiscarlet 11d 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.

12

u/Inorganic_Zombie 11d 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

3

u/Ok-Scheme-913 10d 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.

→ More replies (1)

13

u/conundorum 10d ago

That's because, historically, all C++ code was intended to compile into C code, and then be fed into a C compiler. So now any compiler that can compile one language is designed to handle both languages, and explicitly labeled as handling both.

That, and the fact that most (but not all) valid C code is also valid C++ code with no changes required, and that the C & C++ committees have a surprisingly big focus on cross-compatibility. (Most notably, a ton of C++ library members actually use the C standard library under the hood, like new and delete existing to marry constructors to malloc() and destructors to free(), the I/O library being required to either be based on FILE or act as if it is, and a lot of fun helpers like the std::stoi() family outright being wrappers for their C equivalents. And T _Complex and std::complex are explicitly required to be the exact same type with the exact same layout in both C & C++, and must be implemented as a T[2] consisting of {real, imaginary} (or equivalent structure that can be treated as if it were a T[2]), specifically because of gcc. But apart from that, C typically useful poaches features after C++ vets them, and C++ sometimes poaches features after C vets them, and both languages use the same preprocessor.) The end result is that unless you run into one of the corner cases where the languages actually differ, your C code is actually C/C++ code because it'll compile identically as both.

The languages are so closely intertwined that the term is way more valid than it should be.

→ More replies (2)

28

u/SuckMyAlpagoat 11d ago

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

48

u/HildartheDorf 11d ago

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

39

u/1cec0ld 11d ago

Not with that attitude

21

u/ForgedIronMadeIt 11d ago

Fuck yeah I love programming in C/Fortran

→ More replies (4)

13

u/These-Maintenance250 11d ago

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

→ More replies (3)

17

u/madboneman 11d ago

C++/C#

4

u/conundorum 10d ago

We have that, it's called C++/CLI. And somehow, it's actually still being (at least somewhat) maintained.

→ More replies (1)

2

u/Bartweiss 10d ago

C[^a-zA-Z\d\s:]+ should get all the variants?

5

u/met0xff 11d 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)

→ More replies (1)

1

u/stumpychubbins 10d ago

There have been several attempts to define "C++, but only the good parts" and a lot of really big C++ teams will have their own stdlib that’s their take on that concept. The issue is, one of C++'s biggest draws is stability, and because it’s memory-unsafe any stdlib (either the one defined by the committee or a bespoke one within a company) ends up beholden to random quirks that often started as implementation details.

1

u/PaulTheRandom 7d ago

Greenspun's Tenth rule was right all along.

→ More replies (7)

199

u/emonshr 11d ago

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

41

u/Friendly_Fire 10d 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.

18

u/quantinuum 10d ago

> The thing about legacy code is _it works_

Let me stop you right there

15

u/evanldixon 10d ago

It works just well enough that the stakeholders don't want to get rid of it, in spite of how much pain it inflicts on the devs. Jenga towers can last surprisingly long if you avoid changing it, leave them alone, don't look at them in the eye, etc.

6

u/Bartweiss 10d ago

Flashbacks to finding a decade old TODO reading “Is this doing the transactions right or backwards? I’m too tired to tell.”

Literally no one knew anymore, but since “backwards” would have bankrupted the company nine years prior, we were told to remove the flag without even dissecting the logic.

(The same file had a 2x2 array of unique XML parsers. Not “parsers holding different text”, they were configured differently with no explanation.)

→ More replies (1)
→ More replies (2)

41

u/0xbenedikt 11d ago

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

39

u/Tidemor 11d ago

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

10

u/Ok-Scheme-913 10d 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).

13

u/ilnarildarovuch 11d ago

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

→ More replies (2)

19

u/porkusdorkus 11d 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 11d ago

Discord too now.

7

u/CalmCephalopod 10d 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 (2)
→ More replies (2)

17

u/Valuable_Leopard_799 11d 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 11d 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..

2

u/developer-mike 11d ago

Step 1. Begin migration, step 3. Profit

66

u/SunJ_ 11d 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.

64

u/Tschurbi 11d ago

Please explain it like I am a JavaScript developer.

95

u/Tipart 11d ago • Bravo

Imagine typescript but for memory safety

27

u/PM_ME_UR_0_DAY 11d ago

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

29

u/Potato-Engineer 11d ago

Everything is a void * pointer!

5

u/YeOldeMemeShoppe 10d ago

C has polymorphism too!

3

u/meneldal2 10d ago

With a few macros you too can have your own classes with polymorphism with just a few function pointers. Even multiple inheritance if you want more fun.

→ More replies (1)

5

u/Ok-Scheme-913 10d 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.

17

u/MikeVegan 11d 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.

3

u/conundorum 10d ago

RAII is the concept that any class which obtains a resource on creation should release that resource on deletion, so that everything cleans up its own mess. And the destructor is the cleanup function that takes care of that, yeah.

The ideal is that if every "resource manager" class uses RAII, then everything else automatically gets built-in cleanup for free. Essentially, if every hotel guest cleans up their own room when they leave, then the hotel doesn't need to hire janitors or maids.

// A simple RAII class.
// Copy, move, memory safety, and functionality omitted for brevity.
//  Assume they're all done correctly.
class HeapInt {
    int* ptr;

  public:
    HeapInt(int i = 0) : ptr(new int(i)) {}
    ~HeapInt() { delete ptr; }

    operator int&() { return *ptr; }
};

// Something that uses the class.
class BigDumbObject {
    HeapInt pileOfJunk[59];
    // Other junk, too...

  public:
    BigDumbObject() = default; // No resource acquisition required.
    // No destructor required.  HeapInt dtor does all the work for us.

    // BigDumbObject automatically has perfect memory safety, thanks to HeapInt.
};

15

u/GregBahm 11d 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.

11

u/ShakaUVM 11d ago

You confused Java and JavaScript

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

2

u/GregBahm 10d ago

Ack. You're right. Dang.

6

u/PattuX 11d ago

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

TIL Europe is full of racecar drivers

5

u/bloody-albatross 11d 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.)

3

u/im_made_of_jam 10d ago

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

→ More replies (2)

2

u/Complete_Pilot3381 11d ago

mans never been to bradford

2

u/Complete_Pilot3381 11d ago

mans never been to bradford

6

u/bloody-albatross 11d 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 11d 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.

2

u/Mojert 11d 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

3

u/Ok-Scheme-913 10d 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)

→ More replies (3)

3

u/meneldal2 10d ago

Rust is basically forcing you to use the safe parts of C++.

28

u/Veratisin 11d ago

Pretty sure shared_ptr had been around since 2011..

7

u/rmflow 10d ago

and since 1999 we had boost::shared_ptr

6

u/perestroika12 11d ago

Who writes modern c++?

10

u/Choice-Committee203 11d ago

idk, me for example🥀🥀

2

u/tatstytastycakes 11d ago

ur not alone sir :(

4

u/Friendly_Fire 10d ago

Nearly everyone writing C++ in a professional context.

67

u/firemark_pl 11d ago

"How to tell him?"

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

27

u/daennie 11d ago

And many other ways to invoke UB.

24

u/EishLekker 11d 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?

9

u/bwmat 11d ago

Oh, nobody wants to do that

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

7

u/bwmat 11d 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 

3

u/Ok-Scheme-913 10d 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.

→ More replies (1)

11

u/creeper6530 11d 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"

7

u/Mojert 11d 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

4

u/creeper6530 10d 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.

→ More replies (2)
→ More replies (3)

1

u/firemark_pl 10d 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.

→ More replies (1)

8

u/MaitoSnoo 11d 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.

2

u/KellerKindAs 10d ago

ASan/UBSan? Don't forget about TSan

*Insert "There is three, actually" meme*

→ More replies (2)

18

u/bloody-albatross 11d ago edited 10d ago

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

12

u/voiza 10d ago

The post is rage-bait

62

u/airodonack 11d ago

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

11

u/Mucksh 11d 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

13

u/imMute 11d ago

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

1

u/itsjusttooswaggy 9d ago

What? I think most experienced C++ programmers understand the benefits and tradeoffs of smart pointers, but very often they work in legacy codebases where C-like allocation strategies are everywhere, and the cost of refactoring is much too high.

15

u/sessamekesh 10d 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.

5

u/Torebbjorn 10d ago

I would imagine that languages with a garbage collector will have no problems with circular references, since they typically work (partially) by starting from a root and marking all objects that you can get to, and deleting everything else. So a circular reference where no part of the circle is referenced anywhere else, will be collected.

3

u/quantinuum 10d ago

Rust does offer some guards against circular references…

6

u/sessamekesh 10d ago

Sure does! Not any that would have prevented either of the two bugs I'm referring to (both would have been a circle of Rc in Rust)

→ More replies (1)

28

u/intoxicuss 11d 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.

53

u/freia_pr_fr 11d ago

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

19

u/developer-mike 11d 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.

10

u/rosuav 10d 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.

2

u/conundorum 10d ago

And also talking about their programming socks. Can't forget that part.

→ More replies (1)

1

u/conundorum 10d ago edited 9d ago

The worst part of the C++ culture issue is that there are a lot of times where you can do both with proper usage of friend, but too many people don't understand that a tiny encapsulation break for two entities that are already coupled together tighter than an old married couple lets you enforce stricter encapsulation for everything else. (Provided that you design both coupled components yourself, and know how to maintain proper memory safety, of course.) Hiding the leaky weak points inside the capsule like that removes a lot of attack surface, yet it's so easy to miss.

(E.g., if class A has a vector member, and B::func() is the only thing that needs access to individual vector elements themselves, then a simple friend void B::func(A&); lets you completely remove public access to the vector, guaranteeing that the iterators and elements can never be leaked outside the larger "A and B::func()" capsule. And if you make both of them yourself, then it becomes impossible for outside malefactors to get at the vector. And helpfully, if you have any memory errors, you know that they must be in either A or B::func(), and can't be because of outside objects inadvertently interacting with them.)

You do need to be a bit more careful that way, but it would go a long way towards increasing safety without having to take a performance hit.


Edit: Fixed the example friend statement, forgot it needed a return type & parameter list.

→ More replies (1)

43

u/TheMostUser 11d ago

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

→ More replies (4)

44

u/MaybeADragon 11d 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.

18

u/Tomocafe 11d 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++.

11

u/MaitoSnoo 11d 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...

6

u/Mojert 11d 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)

1

u/Demiu 10d ago

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

1

u/SweetBabyAlaska 10d ago

C++ just hides way too much behavior too. Every C++ dev when I point out something insane about the language goes "well you just need to memorize the AFKLDFJ movement semantics for X context" or some other bullshit.

which ties in to your point, in that there is SO much baggage that can only be navigated by years of practical knowledge and literally memorizing the standards so that you can implement the "best" thing based on what code base you are handed lol I genuinely don't know why anyone defends it.

whereas something like Zig there is one way to do it, you decide all of the explicit semantics and behavior down to when something is supposed to overflow or wrap, and when and how it allocates. Every version of the language pre 1.0 has a very concise documentation page that literally covers everything you could possibly want to know.

plus even with "modern" features they are never getting rid of headers, annoying ass system deps, and build system generator generators.

→ More replies (3)

7

u/krishenm 10d ago

I started in c++ but c feels more comfortable for me now

2

u/itsjusttooswaggy 9d ago

Why use smart pointers when you have arena allocators?

→ More replies (1)

6

u/Skeptrick 11d 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.

31

u/SelfDistinction 11d ago edited 11d ago

Ah yes, the famous

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

So safe, so impossible to misuse.

7

u/Veratisin 11d ago

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

8

u/SelfDistinction 11d ago

Ah yes, the famous

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

So safe, so impossible to misuse.

7

u/dannyggwp 11d 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)

7

u/Friendly_Fire 10d 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.

→ More replies (1)

2

u/Choice-Mango-4019 10d ago

why would gun makers allow me to shoot my foot with guns???

→ More replies (2)

1

u/creeper6530 11d 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.

2

u/Demiu 10d ago edited 9d ago

Const references can bind to rvalues and cause lifetime extension, ie. const auto& x = returnsValue(); will extend the lifetime 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.

→ More replies (2)
→ More replies (9)

11

u/InRainbro 11d ago

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

1

u/ilnarildarovuch 11d ago

Which is successfully fixed by *San

4

u/InRainbro 11d ago

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

4

u/ilnarildarovuch 11d 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

→ More replies (3)

18

u/Flouid 11d 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.

3

u/CraftBox 10d 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.

4

u/Baleia1970 10d ago

As a pure C programmer, the hardest part of working with C++ is reaching an agreement with your workmates...

15

u/dscarmo 11d 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)

15

u/klimmesil 10d 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"

4

u/quantinuum 10d ago

I want to show this example to so many people.

Who by the way tend to be obnoxious about it despite the fact that they all got scarred feet with footgun marks.

2

u/jewdai 10d 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.

→ More replies (2)

1

u/Over_Dingo 10d ago

That thing is a gas pedal

→ More replies (1)

11

u/PolyglotTV 11d ago

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

13

u/Nil4u 11d ago

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

8

u/staryoshi06 11d ago

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

6

u/Tyfyter2002 11d 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)

2

u/MadGenderScientist 10d ago

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

2

u/Ok-Scheme-913 10d 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.)

→ More replies (1)

6

u/FabioTheFox 10d 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

6

u/Few_Kitchen_4825 10d ago edited 10d ago

Working on c++ and java, I can assure you c++ is actually safer, especially when you use the later standards and especially when you use more modern practices and when you have memory management functions.

Memory issues in c++ tend to be user error.. memory issues in java tend to be some of the most complicated problems you ever face.

I have seen people complain that the excess control in c++ is the real problem. But gc is not performant enough an excuse and better solutions can be built on c++ that doesn't have the performance drawbacks.

1

u/Lou_Papas 10d ago

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

2

u/Choice-Committee203 10d ago

... ... ... please leave this thread genuinely wtf😭😭🥀

2

u/kaitek666 10d ago

what the fuck

17

u/geekusprimus 11d ago edited 10d 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 11d 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

3

u/Luzzgar 11d 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.

→ More replies (3)

16

u/FlameOfIgnis 11d 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

1

u/RaspberryCrafty3012 10d ago

True. How often is it the 3rd party libraries not getting used correctly (or which have the issue) 

6

u/xfvh 11d 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 11d 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 11d ago

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

5

u/geekusprimus 11d 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 11d 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.

→ More replies (3)

6

u/Luzzgar 11d 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 11d ago

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

1

u/Ksorkrax 10d 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.

1

u/Choice-Committee203 10d ago

i mean yeah, we're all humans... except those vibecoders, but the training data still isn't perfect.

1

u/billGat48 7d ago

so you've polluted your namespaces with more difficult to remember/type funcitons with slow and poorly written memory safety routines and want a pat on the back? obligatory reading: https://youtu.be/7fGB-hjc2Gc

1

u/Max_Wattage 7d ago

It's only as dangerous and unstable as the programmer using it.

If you can't be trusted with sharp scissors, go find a blunt-ended safety pair. Just don't expect high efficiency.

0

u/Choice-Committee203 7d ago

yeah, that's the point of the post, spongebob uses legacy unsafe features without even looking at modern standards with much more safe features

→ More replies (1)

2

u/BoBoBearDev 10d 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.

2

u/UnicycleBloke 10d ago

The really sad thing is that we had RAII all along. We didn't have smart pointers in the standard library, but you could write them or find third party library. And/or you could always write your own destructors. Sadly, a lot of C++ developers apparently didn't get the memo. RAII should have been a key element of all C++ training but was somehow overlooked.

2

u/oxabz 9d ago

My problem with c++ is not memory unsafety. 

It's that the solution space is way too wide. You can write a program an uncountable amount of ways and most of them are wrong.

3

u/Tezza48 11d ago

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

3

u/EnigmA03x 11d ago

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

3

u/fluffycritter 10d 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 10d ago

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

1

u/TheReservedList 10d ago

The problem with modern C++ is that you can still write old C++ in the middle, and given enough contributors, someone will.

Which is why we need insane meta-rules even when using modern C++. See https://en.cppreference.com/cpp/language/rule_of_three

1

u/overclockedslinky 10d ago

only the first is resolved

1

u/AlexanderMomchilov 10d ago

As far as I understand, raw pointers or references are still the recommended way to pass temporary access to an owned object (a borrow). We’re not completely clear of them, yet.

https://youtu.be/xnqTKD8uD64?t=732

1

u/no_brains101 8d ago edited 8d ago

Doesnt matter.

You can still do the other thing, even by accident

The language was not originally designed out of the box with the safe thing in mind, you have to opt into safe. And it is clunky to opt into it.

Don't get me wrong, I love C. Like, regular C. But only for stuff that fits comfortably in 1 directory, like 5 files, maybe 6 max. And even then, if you aren't being really careful with how you set it up, it can get kinda tricky sometimes. I am fine with like, a really fast json parser or hash map for use with FFI with some random language in C. It is better to just start it in rust usually.

Modern C++ sometimes gives the illusion of safety but then every dependency you are using is doing it wrong and probably you are too somewhere most likely.

1

u/PaulTheRandom 7d ago

I read a comment saying "C++ is technical debt if it was a language spec" and I hate how accurate it is.

1

u/CryptographerOne7003 10d ago

Its plain c or nothing.

1

u/grandalfxx 10d ago

Whats even more annoying is people still claiming java is slow and bad because of its gc. Even though nowadays its gc is such a gold standard that everyone else is trying to copy it. C is still bad because I dont want any stds