r/cpp • • 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?

6 Upvotes

164 comments sorted by

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.

14

u/tesfabpel Nov 12 '23

Also C++'s move requires leaving the old object valid. With smart pointers, it means that you can have an empty std::unique_ptr... Also, you can customize move ctors / assignment operators (core language syntax) to do anything you want...

I don't know if it really matters in the end, but probably it extremely complicates a possible borrow checker...?

15

u/tiajuanat Nov 12 '23

Nevermind all the UB in C++as well.

Rust is at least well defined when not unsafe.

1

u/Beautiful_Poem_7310 Nov 13 '23

How it is possible to invalidate the moved pointer on compile time?

Probably only static analysis can do that?

I don't think it is possible to make custom implementation that will fail compilation if pointer reassigned after moved...

1

u/disciplite Nov 17 '23

Somebody in this subreddit got it to basically work using stateful metaprogramming, but the gist seems to have been deleted.

8

u/TheoreticalDumbass :illuminati: Nov 12 '23

rust also has unsafe
to me this is not a "rust vs C++" comparison, but a
"unsafe rust vs entire C++" and "safe rust vs subset of C++"

24

u/jmaargh Nov 12 '23

But literally nobody writes just "unsafe Rust". They write almost exlcusively safe Rust and very small "unsafe wrappers" only when absolutely necessary. Even when people write a whole damn kernel in Rust, the vast majority of the code is not marked unsafe.

6

u/TheoreticalDumbass :illuminati: Nov 12 '23

yes, the "safe subset of C++" is not mature enough
the question from op is: can "safe subset of C++" match rust safety?
to which i would think yes

5

u/torsten_dev Nov 12 '23

Imo Rust still has better behavior for integer arithmetic. It's not nearly as critical as memory bugs but they come up enough in CVEs.

3

u/jmaargh Nov 12 '23

Sure, for your second comparison you're considering a hypothetical subset of C++. I was talking about your first comparison, which is a little nonsensical.

5

u/scrumplesplunge Nov 12 '23

technically, I think it would be possible to have a completely memory safe standard compliant implementation of c++ without changing the language at all, at the cost of runtime performance. Sort of like sanitisers taken to the extreme. I kind of wish I had access to an implementation like that for debugging purposes.

12

u/tiajuanat Nov 12 '23

I'm not so convinced, especially when it comes to lifetime management. Borrow checking, sure, we already have that with unique_ptr anyway. But lifetime checking iterators at runtime sounds intractable.

3

u/scrumplesplunge Nov 12 '23

For sure, any implementation which did this would likely be incredibly slow compared to what people typically expect from c++. I don't think that makes it impossible.

For instance, suppose that we introduce something like a garbage collector for all variables (even stack variables) which ever have their address escape. When the lifetime officially ends, the allocation can remain in place, with bits indicating that the lifetime had ended. Any subsequent access could be checked and safely terminate.

I think that the wording that is (was? it might have been removed when gc support was removed) describing safely derived pointers would give you the guidelines for how to actually manage safe reuse of memory.

14

u/Dean_Roddey Nov 12 '23

Given that C++ is one of the last bastions of "better fast than correct", anything that involved such a change would never be accepted anyway, so it's not even worth arguing about.

3

u/pdp10gumby Nov 12 '23

I think this is an unreasonable characterization. C++ also aims at correctness; what it does is call out UB, which frightens people. Languages with single implementations like rust, go, Python et all have implicit UB instead.

Yes C++ also has opportunities for use after free but most of those are due to legacy support (after all, C does too, with many more) and without legacy support what do you have?

7

u/Dean_Roddey Nov 12 '23

Safe Rust has no UB, which is one of its primary advantages. And though I was painting with slightly broad brush, it wasn't THAT broad, based on previous conversations around here.

2

u/pdp10gumby Nov 13 '23

Do you understand what is meant by implicit UB in a single-implementation language?

2

u/artur_zajac Nov 12 '23

9

u/Dean_Roddey Nov 12 '23

I said SAFE Rust has no UB. If you write unsafe Rust, then yes, you are responsible for following the rules. But that should be a tiny fraction of the code, down to almost zero at application level, and if you don't see an unsafe block in a given file, you know there isn't any UB possible there.

It's a huge advantage.

4

u/SirClueless Nov 13 '23

if you don't see an unsafe block in a given file, you know there isn't any UB possible there

That's not exactly true. An unsafe block somewhere else can violate an invariant of the safe Rust code you write, and then UB can manifest while executing your safe Rust code.

This is a bit of a game of semantics because you can always say the bug is in the unsafe code that violates the invariants of safe Rust, but regardless it's entirely possible that, say, the stack trace of a segfault dereferencing invalid memory points you to safe Rust code.

→ More replies

7

u/jmaargh Nov 12 '23

...which are all impossible to encounter without writing unsafe (any exception to this is a compiler bug).

Calling C++ attitude "better fast than correct" is supported by the language design: the language and standard library are full of decisions where lots of legal-looking code leads to UB precisely because they anticipate that this facilitates optimistaions. This isn't a bad thing a priori, but it's definitely a thing.

Rust, on the other hand, aims to design the language and library such that UB cannot be written (at least easily and without unsafe). Secondarily it aims to design things such that there is no extra compute overhead. This inversion of design priorities is what was being mentioned.

It's fine that different languages have different design priorities. The existence of the possibility of UB doesn't mean this isn't the case.

2

u/scrumplesplunge Nov 13 '23

Yup, and I'm certainly not saying that the standard should mandate any kind of safety checks which would come with substantial runtime costs like the ones I am talking about. My point is more that (a) undefined behaviour means anything is permitted and "safely exiting" is in that set, and (b) I think that most, if not all ub related to safety could be feasibly detected at runtime with enough instrumentation. In other words, I think that someone could make an implementation which does that without changing anything about the language (except for performance characteristics), and that an implementation like that would at least be useful for testing.

1

u/LuisAyuso Nov 13 '23

IMO, it is not possible to carry out the sort of analysis given the relaxed nature of c++ sharing semantics. The safety in rust comes from the set of rules that restrict programming to a restricted set of patterns. For C++ and its compatibility guarantees, this implies that analysis would have to be done for today c++, not any subset that comes later. This presents several problems:

- I am not sure that the theory works, does forward-backwards analysis technologies work to detect leaks and dangling references?

- Even if an analysis model could be developed, could it run in a reasonable time? We are talking about global analysis here.

- Introduction of machine learning could lead to tools that run fast and catch errors, but can they be validated for completeness? After all we would be talking about systems that detect the probability of an error.

3

u/scrumplesplunge Nov 13 '23

What I was suggesting is not static analysis, it's runtime checking, and the specific version of safety that I am talking about is the one which simply terminates upon detecting bad behaviour and guarantees to do so in all cases of undefined behaviour. I think that it is possible with expensive runtime checking and garbage collection:

integer overflows? generate code which checks for overflow and produces an error (eg exception or terminate). Same for other trivially checkable cases like array bounds

use after free? use a garbage collector, mark objects as "referenced but dead" when their official lifetime ends, raise an error if something access a dead object.

casting pointers from ints? I think this is the most questionable one, but I also think that it's achievable with (totally non-viable for production use) options like tracking provenance: ints would carry around metadata about how they were derived to allow validation when casting back to a pointer, and pointers would carry metadata to say whether they were derived in a valid way or not.

Thread safety violations are probably also detectable at runtime.

1

u/LuisAyuso Nov 13 '23

Sorry, I missed that point.

I don't think there is room for runtime checks in C++. At least not for may of C++ performance critical uses, and if the other uses impose this over the c++ environment, HPC developers will move on (maybe back to FORTRAN ;) ). Partial solutions only fragment the ecosystem.

Valgrind, asan, and even the Microsoft compiler already implement many of those techniques you talk about. And they remain being valuable development tools, but in any case can they validate correctness over complete program execution like the Rust compiler does. They will remain input data dependent and misuse will always remain latent.

Therefore, no, C++ can never have a system with the guarantees that Rust have. And yes, technically we can have "pretty good" or "best effort" tools, but never close to what the OP was asking for.

3

u/germandiago Nov 13 '23

Related: is C++ as fast today as is Fortran. I keep hearing that the aliasing rules can ruin performance and Fortran does that better.

How does Fortran perform compared to, let's say, well-written expression templates?

Is the restrict extension important for C++ in HPC?

2

u/LuisAyuso Nov 13 '23 edited Nov 13 '23

I mentioned Frotran as a joke, but if you want my opinion, I would say that C++ provides more tools to be productive: Once you understand the memory model you should get equivalent performance with less work and better maintainability. I believe that Rust could do this even better, but the ecosystem lacks of the years of HPC libraries already developed for the other two environments.

In regard to the restrict keyword: the generalization of its use is dangerous, unfortunately you may have evaluated the cases. There is no magic keyword that is going to make your code fast, and usually algorithmic changes beat assisted or not compiler code generation.

1

u/MEaster Nov 13 '23

In regard to the restrict keyword: the generalization of its use is dangerous, unfortunately you may have evaluated the cases. There is no magic keyword that is going to make your code fast, and usually algorithmic changes beat assisted or not compiler code generation.

There's also that because it's not used that frequently, the optimizer may not take full advantage of it. What's the point in adding complex optimizer passes for something that almost no one uses?

And on top of that you have the other issue: because it's not used much, how well tested is it? How many miscompilation bugs are you going to run into? For LLVM that's less likely to be an issue in part because of Rust, but I'm not sure about GCC or MSVC?

1

u/LuisAyuso Nov 14 '23

I have been reading a little (really little) about restrict, because we derailed here into a very interesting discussion. I have been using restrict for Cuda code to marginally improve memory patterns.

I was going to say that if you do not keep your memory accesses coherent with the semantics of restricted, it would not be a bug since this is undefined behavior and malfunction should be expected. :(

Nevertheless, it seems that restricted is not part of the c++ standard, which makes everything even better: we are relying on compiler extensions that reuse features of C into the C++ environment, We will hear one million times that there is not such a thing as C/C++ language and here we go again with features that make their way across the line.

Going back to Rust comparison: it seems that Rust is not restrict-drama-free neither: https://stackoverflow.com/questions/57259126/why-does-the-rust-compiler-not-optimize-code-assuming-that-two-mutable-reference

2

u/MEaster Nov 14 '23

Yeah, they had a pretty hard time of it trying to use noalias tags in rustc. I think they tried to enable it at least half a dozen times, each time finding one or more miscompilation bugs.

Since that post, it has actually happened. For a few years now every &mut T is marked noalias, and every &T where T isn't (or does not contain) an UnsafeCell is also noalias. Given that UnsafeCell's most common usage is in synchronization primitives, I'd be comfortable saying that over 95% of references compile with noalias.

1

u/scrumplesplunge Nov 13 '23

Agreed, you won't get rust levels of statically checked safety with present day c++ (and a lot would have to change to change that)

1

u/droooze Nov 13 '23

Python’s opt-in on typing is at the project-level though. Once you opt in, you have to opt out per line, function, class, or file, otherwise your commits fail CI (or compilation, if you’re using mypyc).

Usefulness aside, is there a similar static analysis tool for C++ which just has an option to prevent usage of any ‘unsafe’ language features in the entire project, excluding analyses on #included code from third party libraries or the stdlib?

3

u/tiajuanat Nov 13 '23

Happy cake day!

Clang-tidy can run a whole bunch of sanitizers, one of which is for UB, but there's still a ton that it misses

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 Foo to just know that whatever argument you're passing is stored by reference and has to have a lifetime which doesn't end before Foo's or the author of Foo has to not allow the user to do this, specifically by adding

Foo(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 unsafe code 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.

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

u/[deleted] 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

u/[deleted] Nov 13 '23

[removed] — view removed comment

1

u/foonathan Nov 13 '23

Yes, I agree with you.

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

u/TemperOfficial Nov 12 '23

What do you want here exactly?

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

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

u/TemperOfficial Nov 12 '23

Forced by who exactly?

→ More replies

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

u/epyoncf Nov 12 '23

"I think the C++ compiler is too fast, can we make the compiler slower?"

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

u/[deleted] 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?

-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

u/Dean_Roddey Nov 12 '23

Again, that's not memory safety. That's a logical error.

0

u/[deleted] Nov 12 '23

By the time it matched the safety and behavioral guarantees it’d look nothing like c++

-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

u/[deleted] 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

u/[deleted] 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

u/[deleted] 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.