13 ms·
A brief introduction to C++'s model for type- and resource-safety [pdf]
- pjmlp 11y agoI love the safety path Bjarne, Herb and others are driving the language, but I wonder how much of this work will ever be adopted by the masses, given the amount of "C with C++ compiler" that I usually see. Or code guidelines like the ones from Google, where one is even refrained from using Modern C++ best practices.
- hellofunk 11y agoWhat Modern C++ practices specifically have you found that Google discourages? I'm curious. I'm reading through Scott Meyers' Effective Modern C++ and am finding so much easy and fantastic advice, I wonder if Google is at odds with some it?
- otabdeveloper1 11y ago> I wonder if Google is at odds with some it? It's at odds with almost all of it. Google's standards are C-with-classes based on compiler bugs circa 1999. Despite their (misleading) marketing, Google is still just another enterprisey megacorp employing 30000 blub programmers. Expect the usual 'enterprise' failures.
- hellofunk 11y ago>based on compiler bugs circa 1999 What do you mean by this?
- _yosefk 11y ago> Google is still just another enterprisey megacorp employing 30000 blub programmers. Expect the usual 'enterprise' failures. Ouch! That must have hurt 'em. Of course the original meaning of "Blub" is "anything which isn't Lisp", especially C++ (as well as say Java.) But what the heck, it has a good sound to it. Anyway, I think their C++ style guide isn't bad. As to "modern C++ style", let's wait for a few years, shall we? When the STL came out, auto_ptr and for_each(v.begin(), v.end(), FunctorFromHell()) were marketed as the way to go for a long while; then the usual suspects became a bit more silent. Now again, despite their being a smart for loop, for_each with a lambda (with its crazy capture lists and all) is supposedly considered at least as good as a for loop, and typically better. And you're supposed to use unique_ptr and what-not. Maybe a few years down the road things will look different again. C++11/14 has a ton of weird shit you ought to keep in your mind on top of the weird shit in C++98/03 and many "enterprisey megacorps" seem to apply a restricted subset of C++ rather successfully.
- hellofunk 11y agoIt's hard to deny that there are some really useful new features in modern c++, though. Standardized multithreading primitives is a big one. Smaller ones like scoped enums are useful too. I'm a big fan of lambdas and the ability to use them for things that used to be very awkward to do without them, like std::bind and functors. In all, I think the modern additions are a net positive for sure.
- to3m 11y agoIf you're of this opinion, you should be glad when people don't use them. This can be your competitive advantage.
- 72deluxe 11y agoI would agree with this. I am writing C++03 at work due to lame compilers I am forced to use on Windows, and I really miss little things like std::atomic. Lambdas would mean I could bin all those structs with bool operator()() for find_if that I have to litter my code with.
- scott_s 11y agoI know a lot of people say "Boost is awful", but Boost provides the same atomic interfaces: http://www.boost.org/doc/libs/1_60_0/doc/html/atomic.html http://www.boost.org/doc/libs/1_60_0/doc/html/atomic.html. Quoting from the introduction: "Boost.Atomic is a library that provides atomic data types and operations on these data types, as well as memory ordering constraints required for coordinating multiple threads through atomic variables. It implements the interface as defined by the C++11 standard, but makes this feature available for platforms lacking system/compiler support for this particular C++11 feature."
- 72deluxe 11y agoThanks for the suggestion, much appreciated.
- _yosefk 11y ago
- petke 11y agoWhen I read the Google coding standard I realized I never want to work there. Microsoft on the other hand seems to get cpp. Maybe because herb Sutter has managed to change the culture from the inside. Anyone remember how awful vc6 was back in the day? MS has come a long way. Edit: It seems the standards have changed. It doesn't seem so bad now. They cant use exceptions but they can use some of boost cpp11 and templates. So maybe working at google ain't that bad.
- pjmlp 11y ago- use of pointers instead of references - C style error codes - minimal use of STL - use of templates is frowned upon - C style enums This just of the top of my head, I would need to read it again to see if they changed anything.
- hellofunk 11y ago>minimal use of STL I was recently reading the docs for a physics engine in c++ and they said that its initial implementation used std::vector in many places, but they instead implemented their own in later versions to accommodate maximum "portability and compatibility." I wonder what that means? Since the STL is included in C++ compilers and vector is always going to be there, why would they need to roll their own to make the engine either more portable or more compatible? >use of templates is frowned upon I wonder if this means the writing of templates, or using existing templates. If the latter, maybe like the STL their primary concern is compile times?
- plq 11y agostd::vector spec leaves quite a bit of performance-critical details unspecified. I imagine the allocator behaviour differs enough between implementations that they implemented their own to keep performance in different platforms more predictable. The performance requirements for a physics engine can be quite different from the general case that the std::vector spec is aiming for. I imagine templates are frowned upon for the same reason -- too many moving parts. Otherwise they're perfectly fine to use in projects that have goals other than portably predictable performance.
- hellofunk 11y agoGood points, I hadn't considered that the implementation of a vector could widely vary. That makes sense.
- vvanders 11y agoYup, the spec is also really vague on if clear() actually releases memory. AFAIK the only "correct" way to actually clear a vector is "vec = std::vector<T>()" with the STL.
- lmm 11y agoThey avoid using exceptions, which means avoiding doing work in constructors, which compromises your ability to use RAII, which in turn makes template-style programming much less effective.
- cousin_it 11y agoA static analyzer for a memory-safe subset of C++? That sounds cool. Has anyone downloaded it and tried to break it?
- steveklabnik 11y agoThey have not actually released the tool to the public yet, to my knowledge.
- nickpsecurity 11y agoLook up Iron-Clad C++
- stinos 11y agoOn one hand it's good things like this are written, on the other hand it's a bit of a shame it still gets written. We should have moved beyond that by now, but adoption of modern C++ goes so slow.. Not exactly sure what the reasons are - sometimes it just seems like stubborness to me - I hear 'legacy' often, and yes if your codebase doesn't even compile with the latest compilers than it's a valid argument, but otherwise: it's not exactly hard to interface modern C++ with C-with-classes. Anyway I've worked in multiple teams and after the initial stage of getting overit and doing the right thing none of useever writes code like the 'bad' examples anymore since smart pointers and collections were made commonly available years ago and they solve most of the problems in this pdf.
- greydius 11y agoSafe by convention is a ridiculous notion. I think (and I know this isn't a popular opinion here, but I'll say it anyway) that C and C++ are dying horses; these 'modern' versions and 'best practices' are not adequate solutions, evidenced partly by the fact that we can't even agree on what they should be. The next decade is going to see the rise of systems programming languages with static safety guarantees. Personally, I think Rust has a lot of potential, but we will see.
- 72deluxe 11y agoC++ has had to be backwards compatible for the billions of lines of code written in it. It has managed to introduce new features and safety quite well in view of this. Perhaps the rise of systems programming languages with static safety guarantees is C++ already? You don't have to write it with "old school" methodology just because you can write it with old-school dangerous approaches. I think that C++11 and beyond will do quite well. Sadly here in the UK at least, it has lost vast swathes of the job market to C# (likely because of C++11 taking so long to appear) but there are still a few C++ jobs (for maintaining crusty MFC codebases) or a few that specifically mention C++11. I myself think C++11 is a great language and daily write C++03 at work through gritted teeth. As you say though, we'll see what comes about. It is only a language after all. EDIT: And I will add that C++ does have the benefit of having loads of libraries available to it, including GUI libraries and bindings which makes development a breeze.
- lmm 11y ago> C++ has had to be backwards compatible for the billions of lines of code written in it. It has managed to introduce new features and safety quite well in view of this. Perhaps the rise of systems programming languages with static safety guarantees is C++ already? You don't have to write it with "old school" methodology just because you can write it with old-school dangerous approaches. The very definition of static safety guarantees is that the compiler enforces them, and that's what makes them useful. C++ has great safety guarantees if written correctly - but if you can reliably write code correctly, you don't need safety guarantees in the first place! > EDIT: And I will add that C++ does have the benefit of having loads of libraries available to it, including GUI libraries and bindings which makes development a breeze. There are many libraries, but the important ones have mature bindings from other languages, or at least tools for generating them (e.g. Swig). That said, using them exposes you to the safety risks of C++, so you're often better off rewriting them (e.g. I worked on a Java project that initially used ffmpeg to handle some transcoding tasks - but as a result had to deal with bugs in ffmpeg that took down the whole JVM for particular inputs).
- jejones3141 11y agoCould someone more knowledgeable than me compare and contrast this with Rust?
- steveklabnik 11y agoRust core team member here, so beware of my bias. Compared to Rust, the C++ Core Guidelines: 1. Are still whitepapers, the tool has not been released. 2. Does not protect you from everything Rust does. 3. Incrementally improves on C++, rather than being a whole new language. These points have a number of implications. On the first point, all Rust code that exists today is already written in this style. As the tool still isn't released yet, essentially none (the tool is built based on some Microsoft work that they've been using internally, but other than that) of existing C++ code is following this. This means that even if _you_ use the tool, it doesn't mean your dependencies use the tool. Furthermore, how many people lament that they are still writing C++98 and not C++11, let alone C++14? Once the tool exists, how much code will actually use it? On #2, Herb has said in the past that "data races are off the table" and "dangling pointers in some circumstances are important." I _think_ that in the latter case, he means something akin to what we call "non-lexical borrows" in Rust, so it's not a big deal, but data races are. Rust's version of this concept also provides a foundation for compile-time concurrency errors, and this paper states "Our rule set for concurrency is not yet fully developed." We'll see what they come up with. On #3, this is both an advantage and a disadvantage, and ties into #1. If you have a large C++ codebase, it's not like you're just going to instantly port everything to Rust. Even Mozilla, with Firefox, is taking an incremental approach. This means this tool could have a lot of value for organizations which are using C++ today, in a way that Rust can't. However, as mentioned elsewhere in this thread, I'm not sure how much C++ code will actually pass the tool; rules like this can really change your design, so we'll see. EDIT: One more difference, we use "memory safety" in different ways. They describe their definition on the end of 3.0: > We say that a program is memory safe if every allocated object > is deallocated (once only) and no access is done through a pointer > (or reference, iterator, or other non-owning indirection) to an > object that has been deleted or gone out of scope (and thus > technically isn’t an object anymore – just a bag of bits). We usually describe memory safety in terms of "no data races". Theirs assumes single threading (see above about how concurrency is under-developed here) and we take it into context. Terminology is hard! Finally, I'm glad to see this project develop. I'm glad that the C++ committee is taking safety even more seriously than they have in the past. We all want better software with less bugs.
- zwieback 11y agoI'm glad to see that after all these years Bjarne (and the other authors) have kept up the tradition of clear and concise writing they are known for.
- nickpsecurity 11y agoI'm amazed at how well-written and thoughtful these papers are given the product is a language I oppose. Well, it does have some good ideas. :) However, what made my jaw drop was section 3.2: "a dynamic model" for making the system safe and easily implemented in hardware. The section said Stroustrup deciced not to publish it because it was impractical. One of few times see his name and go "what an idiot..." What wasn't practical in general case or that time period doesn't mean it won't be in future in other circumstances. Good ideas, esp simple solutions, have a way of coming back to us. Specifically, efforts like Cambridge's CHERI processor are looking at minimal modifications to CPU's to greatly increase assurance w/ legacy compatibility. This concept should've been published as there's use in embedded and appliance field where a lot uses subsets of C++. He should've published it. I'm saving the paper for my collection just in case that idea comes in handy.
- pcwalton 11y ago> The section said Stroustrup deciced not to publish it because it was impractical. One of few times see his name and go "what an idiot..." He's right though. Such a system would be slower than a good tracing GC, which completely eliminates these problems and is much easier for the programmer to use.
- nickpsecurity 11y agoIn "hardware" as a minimal processor extension as I said? Pointer checks, etc take almost nothing in HW. Garbage collection schemes have a bigger hit and more complex integration. Hence, having his published report for details to add to collection of lightweight schemes out there for C++ or even another language that might benefit later. That sort of thing happens more than you know in CompSci. Example: One method for Oberon and Java appliances I pulled right out of an old Scheme CPU paper that was also impractical then. Also found a correct-by-construction HW method in same one. ;)
- pcwalton 11y agoSpecifically, how do you do use after free detection in hardware without garbage collection?
- pcwalton 11y agoHere's my biggest question posed yet again, because the paper does not provide an answer to it: The analysis requires that all mutable references be statically proven to not alias on function entry. So how do you call a function foo(T& a, T& b) as foo(x, y) where x and y are instances of shared_ptr<T>? (The problem persists even if a and b are of different types, because a might own b or vice versa.) This is not a contrived example. It is precisely what kept hitting us in Rust with things like @mut and we took years to figure out the best solution (RefCell/Mutex). It comes up all the time because you can't get away from RC--large programs use reference counting a lot, and even if they don't one of the major use cases of systems languages is to interoperate with GC'd or RC'd systems (dynamic languages, COM, Core Foundation) where you don't statically know anything about aliasing. Forbidding these calls statically bifurcates functions into "those callable on shared_ptr" and "those callable on owned or stack-local objects", which is unusable in practice. The only solution we found is dynamic enforcement of the aliasing rules, scoped to reference counted pointers. This indeed works, but it requires overhead. You want this overhead to be opt-in in a low-level systems language, but existing code was not written to opt into this. So C++ will need to backwards incompatibly introduce RefCell/Mutex to support this. The bottom line is that I see a dilemma. Either C++ makes it impossible to use shared_ptr with mutable references, severely damaging usability, or it breaks backwards compatibility by making shared_ptr immutable and requiring dynamic enforcement of the borrow rules for mutable shared_ptr. Either option has huge consequences for existing C++ code.