r/cpp • u/stendhal666 • Dec 04 '17
Safe C++ (with Rust in mind)
I'm having a go at Rust which, as you may know, is a programming language whose target more or less overlaps with C++'s. It's advertised as a system programming language (you can write an OS without too many contortions, for instance), it doesn't come with a garbage collector or costly abstractions, you can use pointers, manipulate concrete types (I mean, corresponding to sthing in the machine). I will spare you further details, but there's a strong design choice which is necessary for me to state for the rest of my post, and which makes the language really different from C++: language, compiler-enforced rules make it impossible 1) to leak resources and 2) to encounter data races. The means to achieve that are actually really simple:
compiler enforced RAII
you can have either as many "non-mutating" handles to a piece of data as you'd like, or one "mutating" handle.
(NB: You can still do unsafe things but you have to disclaim it and insulate that part from the rest of your code).
I'm aware of the Core Guide Lines and the library that comes with them, but there are so many rules in it, of whom so many can't be enforced by a compiler, that they aren't really an answer to what I'm looking for. Besides, they cover by far a wider range of concern.
So what small set of rules, based on what subset of the language, would you choose to obtain maximum safety? By small set, I mean sthing you could keep nailed next to your screen so you don't forget about it :-)
4
u/crusader_mike Dec 04 '17 edited Dec 07 '17
afaik, in Rust you can't handle/survive lack of memory
Edit: tbh, you can't do it (in some cases) in C++ either, lol
4
u/donalmacc Game Developer Dec 05 '17
To be fair, I’m not sure much of my code in c++ could ever survive running OOM.
1
Dec 04 '17
Not without a custom allocator.
1
u/crusader_mike Dec 05 '17 edited Dec 05 '17
How many functions (environment gives you) use custom allocator? how much user code is actually prepared to propagate related error object?
5
Dec 05 '17
There's four amazing things about Rust which I'd love to see being done in C++:
Everything is constant by default, having to declare things mutable instead of having to declare things constant is an amazing design choice. It heavily reduces the amount of errors. In theory one could always use const and constexpr whenever they can in C++ but in practice things slip and sometimes they cause error (not to mention they cause code to be less efficient). I thought this may be solvable with metaclasses, but playing around with the idea I saw it's not as easy as it may seem at first :(
The package&build system. Having a package system is quite valuable, it means there's a centralized place and a standardized way for people to share libraries. It's much more minimalistic and concise than the monstrosity that is Cmake and since most libraries support being built statically and are oss, it means you can compile stand alone binaries as the default, even for large projects, rather than having shared libraries as the "default" and having to struggle if you want a build that statically links everything.
The compiler is more strict in places it should be strict. I'd love for the default behavior of clang and gcc to be compiling with
-Werror -Walland the "unsafe" builds to be done with a flag along the lines of-IgnorErrorThe way it handles move and copy/clone. I'm not saying it's perfect, but it's much better than C++ where some basic optimizations that could easily be compiler implemented instead force you to explicitly use std::move. This, however, would require having a better resource ownership mapping at compile time.
The big problem with the points you mentioned are:
compiler enforced RAII
See the discussion thread started by /u/meh_or_maybe_not
you can have either as many "non-mutating" handles to a piece of data as you'd like, or one "mutating" handle.
This is where, in my opinion, rust oversteps it's boundries. Since a lot of time having two mutating handles makes sense, it's not impossible to have a two mutating handles, you can have mutexes (which in rust will wrap a type), atomics and other concurrent objects... but the implementation feels like a hack and the code that implements them will actually benefit less from compile time checks than the equivalent C++ code.
If in the future architectures will implement mechanisms for synchronization (or mechanisms as to not require synchronization), better than the ones we currently have, Rust's thread-safety may become even more of a nuisance.
8
u/TyRoXx Dec 04 '17
Avoiding leaks is relatively easy in C++: Use RAII, avoid reference cycles by reviewing code using shared_ptr etc very carefully. Use a leak checker like valgrind to run your tests.
Avoid data races by not sharing mutable data between threads. No hidden "worker" threads in god classes. No global variables. Use the Clang thread, address and memory sanitizers to run your tests.
You will still encounter plenty of use-after-free bugs. Use valgrind and address sanitizer to run your tests.
You can get many of the benefits of Rust by having tests and running them with the sanitizers. Also, run your tests with the undefined behaviour sanitizer. You will find a lot of misuse of integer arithmetic.
10
u/Bolitho Dec 04 '17
You can get many of the benefits of Rust by having tests and running them with the sanitizers.
But you need them - in Rust you don't. So there is less overhead if you do it good, but also less error prone, if you do it less responsible ;-)
11
u/throwawayco111 Dec 04 '17
Yeah. His statement was as crazy as Uncle Bob's "You don’t need static type checking if you have 100% unit test coverage".
1
u/Pand9 Dec 04 '17
dangling references are very easy to make, for example. "shared_ptr" is a good prevention. not saying that it's performant, but it's more safe in my experience.
0
u/Z01dbrg Dec 07 '17
One thing I did not see mentioned is references in callbacks/async stuff. By this I mean passing references to callbacks or starting threads with lambdas that capture by reference.
Almost everybody here is a True Believer that will never admit that GC has advantages but this is one place where RAII can not help you since there is no scope in classic sense.
My only advice beside sanitizers is to pessimize for safety if you can afford it. Pass strings and vectors to callbacks by value.
-6
u/Xaxxon Dec 05 '17
If you want me to read what you have to say, have the common decency to write in halfway-decent English.
This was just painful.
6
u/stendhal666 Dec 05 '17
Some like it painful.
PS: I'm French and doing my best. Feel free to correct me, it will be more productive
0
u/Xaxxon Dec 06 '17 edited Dec 06 '17
sthing is not a word.
1
u/destiny_functional Dec 06 '17
he meant "something"
2
u/Xaxxon Dec 06 '17
I eventually gathered that.. but why people think it's appropriate to write like that in a semi-technical large block of text like this is beyond me.
When you want people to read what you're writing, making it as digestible as possible should be your goal.
5
u/destiny_functional Dec 06 '17
It's a reddit post not a blog post.
That said, "sthing" is the only potentially objectionable thing about his original post, and given its innocuousness, your post is just ridiculous. We use abbreviations all the time, "sth" is maybe more common than "sthing", but you wouldn't object to "e.g.", "i.e." or "vs." (or other things).
Deal with it that the internet is used by people from non-English speaking countries (who still speak better English than most native speakers).
Now go play LOL, English monoglot.
1
u/philocto Dec 13 '17
they are not a native english speaker, it's reasonable that they make mistakes.
1
16
u/meh_or_maybe_not Dec 04 '17
In Rust resource leaks are actually easily possible and considered safe, any safe code could call
std::mem::forgetand destructors would never run, or you could create cycles for a less obvious leak.