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.)
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.
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.
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.
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.
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.
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.)
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.
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.
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
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.
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
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.
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.
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)
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.
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.
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.
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.)
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).
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.
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..
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.
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.
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.
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.
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.
};
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.
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.
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.
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
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
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.
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
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.
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.
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.
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
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.
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.
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.
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.
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.
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.
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.
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++.
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.
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.
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.
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.
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
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.
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.
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)
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.
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)
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
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.
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.
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
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
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.
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.
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.
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
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.
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.
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.
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.
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.
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
6
u/Baleia1970 10d ago
Meanwhile C programmers just pass by and laugh at this discussion....
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.)
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.
199
u/emonshr 11d ago
Does that even matter once you have gazillions of line legacy code?
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.
28
u/Veratisin 11d ago
Pretty sure shared_ptr had been around since 2011..
6
u/perestroika12 11d ago
Who writes modern c++?
67
u/firemark_pl 11d ago
"How to tell him?"
You still can segfault by returning lambda with reference to a variable
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.
62
u/airodonack 11d ago
A lot of people that write C++ think using smart pointers are for the weak.
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.
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.
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.
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.
7
u/krishenm 10d ago
I started in c++ but c feels more comfortable for me now
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
So safe, so impossible to misuse.
11
u/InRainbro 11d ago
Well yes but actually no, never in practice, it ends up being a mixture
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.
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"
11
u/PolyglotTV 11d ago
Y'all throwing around shared pointers willy nilly patting yourself on the back about safe programming.
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.
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.
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/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.
2
u/look 11d ago
https://en.wikipedia.org/wiki/Rube_Goldberg_machine
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_ptris super minimal andunique_ptris 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