r/cpp • u/[deleted] • Nov 12 '23
Could c++ have matching safety as Rust?
Afaik, rust‘s safety comes from the strict compiler, couldnt c++ have something like this?
14
u/NilacTheGrim Nov 12 '23
No, nor should it. Let C++ be C++. Use Rust if you want/need/like its safety properties.
29
u/target-san Nov 12 '23
Not a compiler expert, though I doubt so. C++ has too much stuff inherited from C which effectively prevent this, one of such things being copy-by-default.
13
u/pjmlp Nov 12 '23
Only if people are willing to throw away copy-paste compatibility with the inherited C semantics, which is an impossible task, as at this point the constraints will be such that a language designed from scratch with unsafety being opt-in will have better ergonomics.
17
u/tialaramex Nov 12 '23
Firstly and most importantly, safety is cultural. So that's where a solution needs to begin.
But, sure, technologically Rust's compiler implements key language features resulting in safe Rust being an entirely memory safe language. Still, even aside from the need to address cultural problems first, this depends upon foundational practices (which were rooted in that culture) so without the firm foundations you don't achieve compositional safety.
Next most important, the language design, drawing on that culture, prioritises safety - there are two possible ways to handle Rice's Theorem in a powerful general purpose language like Rust or C++. You could, as Rust does, decide that if the compiler can't see why a semantic requirement is met, that's an error and the software is rejected. C++ on other hand says only if the compiler can see why the requirement is not met is it permitted to diagnose an error and reject this software, resulting in the famous IFNDR (Ill-formed No Diagnostic Required) outcome.
You can't keep that C++ decision and have safety. You can't give up semantic constraints in this sort of language (and indeed C++ has added lots more of them in the last years) so that's a radical but necessary change to achieve what you ask.
17
u/Relative_Knee9808 Nov 12 '23
In C or C++, we don't enforce safety through compiler, if we want the compiler to do some memory safety checks, you could use a compiler with this feature, for example clang with --fsanitizer. Also, you can use a dedicted tool for finding potential unsafe part of code, such as cppcheck, valgrind, etc. I feel that the C and C++ world is very decentralized, there is no one big good tool that does it all, we have to know what exactly we are trying to do and find the exact tool for it.
15
u/alexgraef Nov 12 '23
Most use cases for C++ don't want that. You do get nearly perfect object lifetime and memory safety if you just limit yourself to a certain set of C++ features.
And even Rust loses it's safety when you start to talk to components that aren't written in Rust, i.e. basically all of the system and kernel.
7
u/ZachVorhies Nov 12 '23
Wrong. It’s the long tail of unexpected memory bugs that bite us. The type of thing a tool is great at eliminating.
17
u/kam821 Nov 12 '23 edited Nov 12 '23
Most use cases for C++ don't want that.
That is definitely a hot take.
And even Rust loses it's safety when you start to talk to components that aren't written in Rust, i.e. basically all of the system and kernel.
You know that there is something like 'abstraction'?
You can create safe wrapper around unsafe operations to validate the contract and maintain invariants, just like any wrapper built upon C library does.
+ Even deep down in the unsafe hole I didn't see 100% unsafe code, only specific parts that can be tracked down later if something goes wrong.-4
u/alexgraef Nov 12 '23
That is definitely a hot take
Not sure if that is the case. C++ is universally used because of performance reasons. Maybe some people have the luxury of using it because of it's elegance or other more esoteric reasons. But mostly because you need stuff to be fast.
That will very often mean you want to manipulate data directly, in a very efficient manner.
You can create safe wrapper
Then the wrapper itself suffers from the same problem. Also, are you aware that just doing some NULL-checks before passing a pointer to a system call doesn't turn your program intrinsically safe?
16
u/matthieum Nov 12 '23
Not sure if that is the case. C++ is universally used because of performance reasons. Maybe some people have the luxury of using it because of it's elegance or other more esoteric reasons. But mostly because you need stuff to be fast.
C++ was used because of performance reasons, when people wanted a bit more than barebones C.
Rust is just as efficient as C++ or C, though, so performance alone is no longer THE reason. It's generally a combination of performance + X where X may be existing frameworks/ecosystems, existing toolchains, personal preference, existing codebases, etc...
That will very often mean you want to manipulate data directly, in a very efficient manner.
C, C++, Rust, or Zig all allow directly manipulating data.
Then the wrapper itself suffers from the same problem. Also, are you aware that just doing some NULL-checks before passing a pointer to a system call doesn't turn your program intrinsically safe?
Sure. Still easier to double-check a handful of functions than it is to double-check an entire codebase.
After all, don't we use abstractions in C++ (unique_ptr, shared_ptr) precisely because it's easier to have one thoroughly reviewed implementation?
11
u/Dean_Roddey Nov 12 '23 edited Nov 12 '23
And the thing that so many miss is that, if you wrap such a call in a safe Rust wrapper, then the potential issues drop to the called system doing the wrong thing with guaranteed valid parameters. For a well vetted, widely used library, that's a reasonable risk if there's no Rust implementation available in the meantime.
In C++, that underlying library could be passed bogus memory and do horrible things, or could be corrupted by the simplest of memory errors in the consuming code and indirectly do horrible things.
It's a big difference.
7
u/almost_useless Nov 12 '23 edited Nov 12 '23
C++ is universally used because of performance reasons
A very frequent use case is that you need low level access, but want something better than C.
Another common case is probably people that need performance, but not that much performance. Like, Python is way too slow, but if we made C++ safer at the cost of 10% performance, that would also be perfectly fine.
And don't forget that the hot path is usually a very small part of the code, so opting in to speed where it is needed is also a viable alternative for many people.
1
u/kam821 Nov 13 '23 edited Nov 13 '23
Not sure if that is the case. C++ is universally used because of performance reasons. Maybe some people have the luxury of using it because of it's elegance or other more esoteric reasons. But mostly because you need stuff to be fast.
Performance can go hand in hand with security and that these are completely orthogonal.
Security and correctness should always come first and be there 'by default', but it should also be possible to squeeze maximum performance when needed, not the other way around.At some point you have to check preconditions anyway and compilers nowadays are quite good at eliminating redundant e.g. bounds checks.
Most of the time you don't have to be paranoid that a few ifs here and there will affect performance, and in one of those rare cases you can just use unchecked version of a function and comment why it is safe to use it.1
u/alexgraef Nov 13 '23
Performance can go hand in hand with security and that these are completely orthogonal
I could give you plenty of examples where this is not the case. Any simple bounds check already introduce a performance penalty. It's a thing that is not done in tight loops for that reason.
8
u/sellibitze Nov 12 '23
You do get nearly perfect object lifetime and memory safety if you just limit yourself to a certain set of C++ features.
I'm curious: what's that subset?
No non-owning reference/pointer-like types like iterators, raw pointers, "views" in places other than function parameters?
How else would you make sure that things won't dangle?
4
u/alexgraef Nov 12 '23
I'm curious: what's that subset?
It's easier to tell what subset it isn't - every direct memory manipulation for example. Also sharing stuff between threads where only your locking-strategy prevents corruption. You can do that, but at that point the correctness of your own logic is what is the deciding factor.
make sure that things won't dangle?
Smart pointers. What's left then are mostly race conditions/multi-threading issues. That's where your iterators pointing to free'd memory usually come from. Most iterators get invalidated when you manipulate the container in certain ways. Creating a complete list of stuff that's safe vs. what is not safe would be non-trivial. And no one keeps you from using the non-safe stuff.
And you can still get memory leaks from circular references, but tbf even GC languages sometimes struggle with that problem.
There is also some argument to be made about whether de-referencing an iterator causing a C++ exception is much different from other ways the program can react. Although programs should cause errors instead of continuing to manipulate corrupted data.
11
u/tangerinelion Nov 12 '23 edited Nov 12 '23
I get what you're saying and a lot of it comes down "Don't write bad code" and "Understand what you're doing."
If someone's coming from a GC language, C++ is going to cause them to stumble one way or another.
But the issue of dangling is more than just "Use smart pointers." Here's a brain-dead way to get something to dangle without even invoking the heap:
class Foo { const int& m_x; public: Foo(const int& x) : m_x(x) { } int x() const { return m_x; } }; int main() { Foo x(42); std::cout << x.x(); // Oops, reference to temporary. }It's either on the user of
Footo just know that whatever argument you're passing is stored by reference and has to have a lifetime which doesn't end beforeFoo's or the author ofFoohas to not allow the user to do this, specifically by addingFoo(const int&&) = delete;Alternatively we could imagine a language which simply didn't allow
Foo x(42);to compile, and instead forces one to write
int value = 42; Foo x(std::cref(value));thereby making the way that arguments are passed around very explicit, at the cost of increasing noise and verbosity in the codebase.
2
u/alexgraef Nov 12 '23
You are right in that C++ has many pitfalls. You can still leave instantiation to C++ containers and smart pointers, and avoid unmatched calls between new and delete.
Also, the problem with external components stands. I'm more of a C# boi, and I have no trouble crashing my applications by doing stupid things with COM components for example. Despite the fact, that C# provides wrappers for them.
7
u/UnicycleBloke Nov 12 '23
Not to be controversial but do we really need it?
Memory safety issues are a rare feature of my development experience. I'm a reasonably competent dev who tries to pay attention to details and make consistent use of RAII and other sensible practices, but I'm certainly not some kind of genius savant coding demon who never makes mistakes.
I've spent some time learning Rust and found that the borrow checker was pretty much it's least interesting feature. When I wrote some non trivial code in Rust, I felt that the checker was actually too restrictive and got in my way. That is likely because I'm familiar with C++ idioms but not Rust idioms, but I wondered whether the flexibility of the language had been compromised in order to make the borrow checker possible to implement.
I mostly work in the embedded domain. As I understand it, all my drivers and other low level items would in any case necessarily bypass the checker in some places by using unsafe code.
13
u/matthieum Nov 12 '23
That is likely because I'm familiar with C++ idioms but not Rust idioms, but I wondered whether the flexibility of the language had been compromised in order to make the borrow checker possible to implement.
It has been restricted. Static typing -- such as borrow checking -- is either overly restrictive or too permissive. In order to ensure safety, Rust had to err on being more restrictive. Or in other words, it's hard to codify all the possible ways to code things.
I mostly work in the embedded domain. As I understand it, all my drivers and other low level items would in any case necessarily bypass the checker in some places by using unsafe code.
I put the emphasis for you: "in some places" is the very, very, important part.
For example, Redox is a micro-kernel coded in Rust. As a micro-kernel, it mostly preoccupies itself with all the low-level complex bits, and delegates much of the higher-level functionality to userland. Yet, despite being so low-level, the amount of
unsafecode is about 10%. It's quite incredible that 90% of a micro-kernel can be safe.In the embedded world, there's been a strong push to create safe-to-use HAL and safe-to-use realtime OSes, so that once those implementations are vetted, the entire rest of the embedded application can be written in safe code.
"In some places" really means: unsafety can be safely encapsulated, dealt with once and for all, audited once and for all, etc...
-1
u/UnicycleBloke Nov 12 '23
My original point was that memory safety issues don't crop up much for me in any case. I evaluated Rust and determined that it is interesting but not remotely compelling. I do however see why C devs might fall in love with it.
Oddly enough I am about to start a job in which some projects are in Rust. I suspect I will spend far longer trying to satisfy the compiler than I would dealing with actual memory issues were the code in C++. At least until I become a bit more Rusty.
8
u/jmaargh Nov 12 '23
I suspect I will spend far longer trying to satisfy the compiler than I would dealing with actual memory issues were the code in C++.
I doubt it. My experience of managing people moving from C/C++ as newbies into Rust projects is that good developers are often more productive in Rust than they were in C & C++ within a few weeks, from scratch. If you're working with it full-time the learning curve really isn't that long and all of the modern conveniences, tooling, and yes the pedanticness of the compiler actually increases productivity by nipping potential problems in the bud.
1
u/UnicycleBloke Nov 12 '23
Until a few days ago, I was certain I would see out my career adding value with my decades of C++. It'll be interesting.
5
u/jmaargh Nov 12 '23
Good luck! I genuinely hope it goes well. Feel free to drop me a message if there's something you're finding confusing or need some advice.
0
u/matthieum Nov 13 '23
Having performed the transition from C++ to Rust, don't worry, your decades of C++ will serve you well.
Rust mostly enforces what would have been good practices in C++ -- most of which you should already know and practice -- so it regularly feels like just a different syntax for expressing the same operations.
5
u/Dean_Roddey Nov 12 '23
You are missing a big part of the point. It's not just about you. It's about you and all the other people you work with. Even if they are all very conscientious and 100% every day (not likely), as soon as multiple developers are involved, communications issues come into play, code gets changed by people who didn't write it and may not fully understand all the intricacies, last minute refactors driven by market realities, code you use gets changed without you being aware of it, and on and on.
It's for all these things that languages like Rust are the right solution. As I've said before, I have a personal C++ code base of over a million lines. It was a very complex product in the field for a long time, and was highly stable. But it was written under almost ideal conditions, and a LOT of that time was spent just making sure I didn't make mistakes. That time could have been spent on product functionality instead and I may have keep a few more mm of heart tissue intact for later in life.
1
u/UnicycleBloke Nov 12 '23
OK. I'm not a Luddite. The point about my personal experience is that I'm nothing special. I suppose have been somewhat fortunate to work alone or in quite small teams of competent devs. Using Rust in my new job will surely be interesting.
2
u/matthieum Nov 13 '23
I suppose have been somewhat fortunate to work alone or in quite small teams of competent devs.
That's a big factor.
In my experience, the issues with C and C++ crop up at scale due to the knowledge (assumptions) you have about how the application is structured, the contexts in which each piece of code is called, etc...
This knowledge, unfortunately, erodes:
With codebase size: the bigger the project, the harder it is to keep it all in your head.
With team size: the more teammates are constantly changing things around, the harder it is to keep up with the rate of changes.
With time: the longer ago, or the more projects you participated in in the meantime, and the harder it is to get back to a given codebase.
If you only have to handle the one small codebase with a small team, it'll be much easier, to the point that you'll wonder what everyone else is harping about.
2
u/Full-Spectral Nov 13 '23
Even in just a single person setup it can make a real difference. I'm creating a new Rust based system that's going to end up quite large and which is a sort of ground up (where of course 'ground' is a relative term) highly integrated system, where most everything is either my own or wrapped runtime stuff.
Since it's a new system and I'm sort of working things out, I've been doing many really significant refactorings. Never in any of those have I worried about introducing either memory errors or threading issues, something that would have been all over me if this was a C++ system, to the point that I probably would have not done some of those refactorings.
9
u/pjmlp Nov 12 '23
Depends how far governments will go regarding safety clearance for software delivery.
3
u/RadioMelon Nov 13 '23
One of the most reliable tools you can use are smart pointers.
They aren't perfect but they ARE a massive improvement to memory safety, if a bit demanding on memory.
5
u/Mrkol Nov 12 '23
Yes. Go read Sean Baxter's twitter for update progress on adding a borrow checker to Circle (an experimental C++ compiler with a ton of extensions) https://x.com/seanbax
6
u/CandyCrisis Nov 12 '23
Note that this isn't C++ (it introduces a whole new class of things) and wouldn't be compatible with anything in today's C++. It's super cool though, very impressive stuff.
7
u/Mrkol Nov 12 '23
Circle is a compliant C++ compiler, and the borrow checker extension IS compatible with standard C++. The plan seems to be to propose its standardisation when it's finished.
5
u/CandyCrisis Nov 12 '23
That doesn't invalidate what I said--Foo^ things don't exist anywhere in today's C++ code so it's not interoperable with any of it. If you can convert a Foo^ to a Foo* you regain interoperability but can no longer trust the memory safety. It might be easier to rewrite C++ code into Foo^ style than it is to rewrite it in Rust, but that's an unknown, and once you do, that code becomes incompatible with pre-borrowing C++.
Another important question: is this compatible with the standard library? Will vector<> be redesigned in terms of Foo^ instead of Foo&? Iterator invalidation is still a hard problem to solve and it's not clear to me that this solves it (but it might?)
2
u/Mrkol Nov 12 '23
Well yeah, that's the idea, you gradually rewrite your codebase to be borrow-checked, by marking stuff as safe one by one. You can opt out of safety for specific legacy modules if you need to, same as rust.
1
u/CandyCrisis Nov 12 '23
If those modules share data structures it might not be so easy. Remember, "simple" things like linked lists are difficult in a borrow-checked world.
4
u/Mrkol Nov 12 '23
Write them in unsafe mode and heavily unit test then, what's the problem? Sean's project is literally rust in C++, and rust is doing pretty good with the safe/unsafe model
1
u/pjmlp Nov 13 '23
Plenty of compiler specific stuff in clang, GCC, MSVC, ICC, whatever else, don't have representation in ISO C++.
I always find quite tragic that some blessed language extensions are "C" or "C++", while the ones one doesn't like, aren't.
5
u/foonathan Nov 12 '23
Yes.
We can copy/paste Rust style references into C++ and implement lifetime rules. It's significant engineering effort, but doable.
It would break all existing code, though.
10
Nov 12 '23
[removed] — view removed comment
3
u/foonathan Nov 13 '23 edited Nov 13 '23
It's worse since you're missing the Rust ecosystem, package manager, traits, pattern matching, ADTs, ...
4
5
u/Dean_Roddey Nov 12 '23 edited Nov 12 '23
You could do it, at which point it will no longer be C++, so my argument is don't do it. Rust already exists, there's no point spending a decade creating a new language that both isn't C++ anymore, and hence will have much of the same rewrite burden, and which still doesn't have a lot of other benefits that Rust also has over C++. Throw those in there also, and now it's even more a completely different language. And, in the meantime, almost everyone who wants those things will have long since moved to Rust anyway.
And of course the entire standard library would have to be jettisoned and a new one written, so add another decade after the new language development decade. At that point C++ will be in exactly the same position COBOL is now. It will purely exist to support crusty old legacy systems, and for some individuals to do fun time projects in the manner of their forefathers.
And, you'd still have to interact with old C++ code for a long time, which would mean two entire runtime libraries that you have to interface between across those boundaries, with the endless problems that would entail.
It's just not worth bothering.
2
u/TemperOfficial Nov 12 '23
If that's the case then why are you here?
5
u/Dean_Roddey Nov 12 '23
I've written C++ all my life, and I still do it (unfortunately) for money at this time. So I have some vested interest in where it goes.
-6
u/TemperOfficial Nov 12 '23
So you spend all your time telling people that C++ is over and they should move to Rust?
Doesn't really make much sense to me.
If Rust is inevitable then theres no point saying anything. If you are very invested in C++ surely you'd be arguing the opposite of what you are arguing here.
9
u/kahomayo Nov 12 '23
If my boss has me drive a car without seat belts, am I not to advocate for the use of seat belts in cars? If I think seat belts will eventually be mandated because the lack of seat belts causes harm, am I not to advocate for seat belts to become mandatory now, before more people are harmed by their absence?
And honestly, a lot of the skills one learns from driving without a seat belt transfer to driving with a seat belt.
-4
4
u/Dean_Roddey Nov 12 '23
Yeh, I think they should move to Rust where it's practical. Of course it makes sense. I have to write C++ now because the company I work for has an existing code base. If I have a chance, I'll push them to Rust, and I think that clearly anyone starting anything new should use Rust.
My belief about C++ is that they should do small, obvious things that will allow the existing unsafe code that we (for a while yet) have to write Rust on top of can be made safer in the meantime. I don't think they should waste a decade plus creating a new language that will be obsolete by the time it it rolls out the factory door.
-3
u/TemperOfficial Nov 12 '23
But then shouldn't you be in the rust subreddit?
12
u/Dean_Roddey Nov 12 '23
No.
-1
u/TemperOfficial Nov 12 '23
Your belief is that we should write Rust instead of C++. Why are you here? I mean that as a genuine question. What are you getting out of this?
9
u/jmaargh Nov 12 '23
While it's true that subreddits can turn into fanboy echo-chambers it's not mandated that they should be (or desirable).
Where does the desire to never hear a negative opinion about a thing that you like come from? It's truly silly. Welcome reasonable opinions from outside of your bubble and consider them: whether you decide you agree or disagree afterwards you'll learn something either way.
0
u/TemperOfficial Nov 12 '23
Nah this is more about the fact that wanting Rust to be C++ can't/won't happen.
It would serve everyone better if the people who love Rust just ditch C++ and leave C++ to people who don't care much about Rust.
All I see nowadays is just a bunch of people who dislike C++ because it isn't Rust.
There aren't any C++ fanboys here.
→ More replies (0)3
u/Dean_Roddey Nov 12 '23
I already made that clear. For some time now, we will be forced to write Rust on top of C/C++ code. I am arguing for not wasting a decade and huge resources on something that will probably never meet its objectives, but instead of make simpler changes that can be done now, that can be reasonably retrofitted.
For instance, standardizing something along the lines of Microsoft's annotations system would be something that could be done in some reasonable time frame and could be incrementally applied to most C++ code bases to good effect. It would provide much more semantic information to the compiler.
For any Rust that has to be built on top of that C++ code, it will benefit as well.
1
3
u/amineahd Nov 12 '23
Isnt Rust safety only regarding type and memory safety?
2
u/NilacTheGrim Nov 12 '23
Yeah. You can still have bugs that lose people money in a finance app or that blow away the disk in a disk-manipulation app.
6
u/Dean_Roddey Nov 12 '23
But a big difference is that logical bugs can be tested for, memory and synchronization bugs can't. And, not a small thing, if you aren't spending so much time being sure you are safe, you can spend more time worrying about getting the logic right.
0
u/NilacTheGrim Nov 13 '23
memory and synchronization bugs can't.
Ever hear of sanitizers?
6
u/Full-Spectral Nov 13 '23
They will only catch something that actually happens. That's the great thing about these types of bugs. They may only happen under particular circumstances and you can't know ahead of time what those are. With a lot of extreme unit and stress testing you could catch a lot of them, but you'll never really know. But somehow customers seem able to create the right conditions at will. It's a mystery.
3
u/NilacTheGrim Nov 14 '23
they may only happen under particular circumstances and you can't know ahead of time what those are
For sure. That's equally true of business-logic fuckups as well. Bugs are bugs, is the lesson here. And yes, agreed, you never truly know until the software is in the wild and users create situations that your code never was tested for or you never imagined. It's almost bound to happen with a sufficiently complicated system.
Yes, of course, borrow checker and compile-time restrictions offered by e.g. the Rust language def. help with some classes of bugs for sure nobody disagrees.
I would argue that sanitizers for C++ are like 99.9% likely to catch most things. But of course there may be nooks and crannies of codepaths that are not triggered or situations not triggered that sanitizers may miss. (But then again that's true of business logic bugs too so..)
All we can say is that ultimately bad brain = bad code = bad software... so... it's still up to the programmer to develop software responsibly and carefully... and there is no magic bullet. All we can do is use tools that can help reduce probability of disaster (whether they be strict static checking languages like Rust, or sanitizers in a more liberal language like C++, etc).
1
u/Full-Spectral Nov 14 '23
It's more than that. If a memory or threading error occurs in Rust, you know it immediately, at compile time, before you even check it in, before you yourself even waste any time on it.
In C++ you may not find out until the release is in late stage, system level testing and have to go back and fix things and re-test. And, in the meantime, it may have been causing other developers problems that they spent time on for no reason, and possibly even compensated incorrectly for.
And the situations that can cause such memory and threading issues are endless, whereas the actual business logic, for a fairly well developed product, will have long since have had tests in place that can have a high probability of catching issues, because you are testing the known path, of these things go in and those things come out.
3
1
u/TemperOfficial Nov 12 '23
Yes.
Ban heap allocation.
Only allocate from a buffer that is bounds checked.
You now technically have the same level of memory safety as Rust.
7
u/CryZe92 Nov 12 '23
You really don't. You are missing the mutable xor aliasing rule and closely related the Send / Sync traits for thread safety. Also that doesn't even buy you use after free safety. So you literally didn't gain a single aspect of Rust's safety story.
0
u/TemperOfficial Nov 12 '23
Use one thread.
The question is can you achieve memory safety with C++. The answer is yes.
You are answering a different question.
7
u/jmaargh Nov 12 '23
Use one thread.
Doesn't save you. Doesn't prevent you passing overlapping mutable pointers to a function that doesn't expect overlaps. You still have to deal with signals from the OS or processor interrupts (for not embedded or embedded respectively): they have exactly the same race problems as threads. Does nothing for use-after-free. You can still return references to temporaries. I could probably go on.
1
u/TemperOfficial Nov 12 '23
Well I'm being somewhat facetious.
However, if you actually want memory safety to an acceptable degree, you ban pointers and all memory access goes through an index/handle.
Also, Rust doesn't solve race conditions.
4
u/jmaargh Nov 12 '23
Well I'm being somewhat facetious.
Haha, fair.
... if you actually want memory safety...
There does exist a "memory safe" (for the Rust definition thereof) subset of C++, but I think it removes almost all of the language (references as well as pointers). I'm sure somebody's written an interesting academic paper on exactly what that subset is, but I doubt it's very useful!
Also, Rust doesn't solve race conditions.
Not "race conditions" no (depending on how you define that), it solves data races. OS signals and processor interrupts have the same data race problems as single-core preemptive threads.
1
u/PancakeFactor Nov 12 '23
Could? Sure. Theres lots of changes to be made that could get us really darn close if not there.
Will it ever happen? no. almost all of those changes would break backwards compatibility.
1
u/SergiusTheBest Nov 12 '23
I think it's possible to create a safe subset of c++ that will match Rust safety. Currently the compiler has no all necessary information to ensure safety.
1
u/Lance_E_T_Compte Nov 12 '23
Look at CHERI from the University of Cambridge. Codasip and lowRISC have commercial chips. New ABI, but they have gcc/llvm support.
1
u/LeeHide just write it from scratch Nov 13 '23
You could take a subset of C++ and formally verify it, probably, like SPARC for Ada, call it SPOCK for C++ or something.
The IMO best solution would be better Rust and C++ interop, so you could stop having to "rewrite it in Rust" and instead slowly migrate important / difficult to reason about parts of your code to Rust.
1
u/fdwr fdwr@github 🔍 Nov 13 '23
better Rust and C++ interop
Historically I've observed that community to be hostile to that idea, for whatever reason 🤷♂️, but I really appreciate seeing that some other languages like Swift are taking on more C++ integration, because yeah, the "rewrite it in xyz" mantra is madness that fails to consider all the other factors (builds, tooling, packaging, depedencies).
1
u/jmaargh Nov 14 '23
Where have you heard that? The tools for managing C++ interop or very popular in Rust
2
u/fdwr fdwr@github 🔍 Nov 14 '23
I followed the Rust reddit for 2 years. So, it was an observation of accumulated comments and reactions. I would love to have recorded a corpus of direct quotes for this moment in the future to provide to you, but all I am left with is the memory of community sentiment :( (or at least sentiment of those who were commenting, as there could have been many who actually wanted C++ interop who were quiet).
1
u/jmaargh Nov 14 '23
That's unfortunate, I'm sorry that was your experience. Mine is that cxx (a C++ interop generator) is one of the best regarded crates in the ecosystem (featured on blessed.rs, for example). In fact, good FFI interop is one of the things I've used when advocating for Rust in the past (C interop is top-tier, Python very close, C++ very good considering the irreducible differences in semantics of the languages).
I'm sure there's more from both the C++ and Rust sides that could be done. What do you find is missing right now?
1
u/fdwr fdwr@github 🔍 Nov 14 '23
Please continue to advocate for language interop. I have a C++ library that I want to be callable from C#, Rust, Python, Lua, and so when I reach the point of Rust callability for it next year, I may find some missing aspects to relay to you. Cheers jm.
-9
Nov 12 '23
Code safety starts with the person that writes the code, not the language or compiler.
10
u/pjmlp Nov 12 '23
The language and compiler help the person that writes the code to behave accordingly.
13
u/schteppe Nov 12 '23
Yes, but the person writing the code gets help from the compiler and the language. If the language doesn’t allow you to dereference null pointers, you won’t have problems with null pointer crashes.
6
u/sam_the_tomato Nov 12 '23
Code safety might start with the coder, but it ends with the compiler.
The aviation industry learned the hard way that even the most experienced pilots are human and make catastrophic errors from time to time, which is why modern airplanes have so much automation and fail-safety.
Experienced coders are no different, they make mistakes at a predictable rate, just lower than that of an amateur.
5
u/jmaargh Nov 12 '23
"This safety feature is not foolproof therefore it is useless". Excellent take. Truly inspired. /s
12
u/lightmatter501 Nov 12 '23
The language and compiler certainly help. Both MS and Google have large C++ codebases and can’t find people who don’t write bugs. After a certain point we need to have a machine check everyone’s work.
I’m strongly of the opinion that C++ needs epochs or a cpp2 which throws out the stuff you shouldn’t use anymore, or hides it behind a std::unsafe namespace.
4
u/DanielMcLaury Nov 12 '23
Okay, so write everything in straight machine language. Or do you think that would result in writing bugs far more frequently?
-6
-2
u/FlyingRhenquest Nov 12 '23
You can write safe code in C++, you just need discipline and knowledge. Java was supposed to be safer than C++ as well, but at the end of the day it just opened up entirely new classes of security problems which required you to have discipline and knowledge to write safe code. Do you think Rust is any different? If you don't have the knowledge and discipline to write safe code in C++ or Java, what makes you think you will in Rust?
9
u/Dean_Roddey Nov 12 '23
Not the kind of safety being discussed here. You are talking about logical errors, not memory safety. Rust gets rid of the memory safety issues. Yes, logical errors still need to be dealt with, but that will always be the case. But logical errors can be tested for, and you have more time to put into the logic if you aren't constantly spending time insuring you are manually doing the right thing wrt to memory safety.
-2
u/FlyingRhenquest Nov 12 '23
Yeah, java was supposed to have memory safety too. Applications would end up just leaking memory until the systems crashed. I've worked at more than one company where the solution to that was to just reboot the servers every few days. No discipline or knowledge on display there.
9
0
0
-3
u/justkdng Nov 12 '23
you can achieve a comparable level of safety by enabling all compiler warnings and treat warnings as errors.
-2
u/helloworld1101 Nov 12 '23
Not too related, but what are the aspects that C++ is still better than Rust?
4
u/simonask_ Nov 12 '23
Some algorithms and data structures are easier or more succinctly expressed in C++ (many things with intricate internal references or ambiguous ownership). Some programming patterns are much more easily expressed in C++ (OOP with inheritance, certain kinds of metaprogramming).
These haven't been blockers for Rust yet. They're all the result of Rust making different tradeoffs than C++, and there are upsides to those tradeoffs too, so it's all YMMV.
4
u/Kevathiel Nov 13 '23
Rust still lacks some features. There is no placement new, const float arithmetic, or specialization.
While they all have been on Rust's todo-list, they made barely any progress at all in the past years, and are blocked by seemingly unsolvable issues. Rusts focus on correctness could mean that certain things won't be implemented at all, because it is impossible to settle on a solution without edge cases, so experimental support might all we get.
-9
Nov 12 '23
[removed] — view removed comment
4
u/jmaargh Nov 12 '23
"Remove unsafe features" - For Rust's definition of "unsafe" that's almost all of C++
-4
Nov 12 '23
[removed] — view removed comment
8
u/jmaargh Nov 12 '23
You have entirely misunderstood me. I mean that (defining "unsafe" the way that Rust does), to "remove unsafe features" of C++ means to remove almost all of C++ because C++ was designed in an incredibly unsafe way.
For the rest of your comment, it's such a trolly bad take it's difficult to know where to start, so I won't bother.
-3
Nov 12 '23
[removed] — view removed comment
5
u/kahomayo Nov 12 '23
Are you relying on operator[] not being vulnerable to timing side-channels?!? There are architectures where not even operator+(int, int) is constant-time (wasm), and that's before taking caches and compiler optimizations into account. I don't think any part of C or C++ are guaranteed to be free from timing side-channels and that's part of why a lot of crypto code is assembly.
1
116
u/tiajuanat Nov 12 '23
Fundamentally no.
The Rust language itself is based on an opt-out mentality wrt safety.
C++ has been opt-in.
It's like Python being opt-in on typing. Yes, it helps, but at the end of the day, you're not forced to sign a waiver every time you don't want to use the type system.
So long as C++ keeps supporting plain old pointers, we won't have the same safety.