11 ms·
Why Safety Profiles Failed
- alilleybrinker 2y agoThe article makes the particularly good point that you generally can’t effectively add new inferences without constraining optionality in code somehow. Put another way, you can’t draw new conclusions without new available assumptions. In Sean’s “Safe C++” proposal, he extends C++ to enable new code to embed new assumptions, then subsets that extension to permit drawing new conclusions for safety by eliminating code that would violate the path to those safety conclusions.
- steveklabnik 2y agoReally glad to see this thorough examination of the weaknesses of profiles. Safe C++ is a really important project, and I hope the committee ends up making the right call here.
- wyager 2y ago> Safe C++ is a really important project What makes you say this? It seems to me like we already have a lower-overhead approach to reach the same goal (a low-level language with substantially improved semantic specificity, memory safety, etc.); namely, we have Rust, which has already improved substantially over the safety properties of C++, and offers a better-designed platform for further safety research.
- steveklabnik 2y agoI am pro any movement towards memory safety. Sure, I won't stop writing Rust and start moving towards C++ for this. But not everyone is interested in introducing a second toolchain, for example. Also, as this paper mentions, Safe C++ can improve C++ <-> Rust interop, because Safe C++ can express some semantics Rust can understand. Right now, interop works but isn't very nice. Basically, I want a variety of approaches, not a Rust monoculture.
- nicoburns 2y ago> But not everyone is interested in introducing a second toolchain, for example. Not that this invalidates your broader point about Safe C++, but this particular issue could also be solved by Rust shipping clang / a frontend that can also compile C and C++.
- steveklabnik 2y agoI have long thought that rust needs to copy Zig here but nobody seems to want to do it, so…
- anp 2y agoI’ve often joked that rustup with a little buildscript copy/paste to use the cc crate could be the fastest way to set up a C++ toolchain and project on lots of systems, but I also haven’t received much enthusiasm on the topic from people involved more with upstream.
- citelao 2y agoI did that yesterday with a project: I took a Rust package that compiled a C project, then had the Rust project generate a C-compatible DLL that I could consume in dotnet. It was so much easier (for me; I am bad at build systems) that I plan to do that for future projects. There’s just something about `cargo run`…
- evntdrvn 2y agohow about just having rustup bundle zig as part of its tooling… It would make getting Rust going on Windows ten times easier, among a bunch of other benefits.
- sitkack 2y agopip install rust Would be awesome!
- estebank 2y agoOn the one hand, I think that it would be a winning strategy. On the other, that effectively turns C++ part of the Rust language. And that is even before looking at the need to extend the Rust compiler to express things that the Rust language doesn't have/need but C++ does, like move constructors.
- tptacek 2y agoThis is a thread about a C++ language feature; it's probably most productive for us to stipulate for this thread that C++ will continue to exist. Practical lessons C++ can learn moving forward from Rust are a good reason to talk about Rust; "C++ should not be improved for safety because code can be rewritten in Rust" is less useful.
- wyager 2y agoActually, this subthread is about whether this is a "really important project"
- tptacek 2y agoto the C++ language
- pjmlp 2y agoEspecially because many of us security minded folks do reach out for C++ as there are domains where it is the only sane option (I don't consider C a sane alternative), so anything that improves C++ safety is very much welcomed. Improved C++'s safety means that the C++ code underlying several JVM implementations, CLR, V8, GCC and LLVM, CUDA, Unreal, Godot, Unity,... also gets a way to be improved, without a full rewrite, which while possible might not be economically feasible.
- SubjectToChange 2y agoThings like web browsers will continue to have millions of lines of C++ code regardless of how successful Rust becomes. It would be a huge improvement for everyone if such projects had a tractable path towards memory safety
- wyager 2y agoAs this article discusses, it's not really viable that existing codebases will be able to benefit from safe C++ research without massive rewrites anyway
- SubjectToChange 2y agoYes, absolutely. But it is still easier and more practical for those codebases to write new functionality in a Safe C++ dialect than it would be to use Rust.
- akira2501 2y agoCool. Do you mind if we have more than one approach?
- wyager 2y agoYeah, it does not matter to me, but that wasn't what we were talking about
- alilleybrinker 2y agoNot everything will be rewritten in Rust. I've broken down the arguments for why this is, and why it's a good thing, elsewhere [1]. Google's recent analysis on their own experiences transitioning toward memory safety provide even more evidence that you don't need to fully transition to get strong safety benefits. They incentivized moving new code to memory safe languages, and continued working to actively assure the existing memory unsafe code they had. In practice, they found that vulnerability density in a stable codebase decays exponentially as you continue to fix bugs. So you can reap the benefits of built-in memory safety for new code while driving down latent memory unsafety in existing code to great effect. [2] [1]: https://www.alilleybrinker.com/blog/cpp-must-become-safer/ https://www.alilleybrinker.com/blog/cpp-must-become-safer/ [2]: https://security.googleblog.com/2024/09/eliminating-memory-safety-vulnerabilities-Android.html https://security.googleblog.com/2024/09/eliminating-memory-s...
- wyager 2y ago> Not everything will be rewritten in Rust. Yeah, but it's also not going to be rewritten in safe C++.
- alilleybrinker 2y agoThere’s likely some amount of code which would not be rewritten into Rust but which would be rewritten into safe C++. Migrating to a whole new language is a much bigger lift than updating the compiler you’re already using and then modifying code to use things the newer compiler supports. Projects do the latter all the time.
- pavon 2y agoWhy not? C++ has evolved over the years, and every C++ project I have worked on, we've adopted new features that make the language safer or clearer as they are supported by the compilers we target. It doesn't get applied to the entire codebase overnight, but all new code uses these features, refactors adopt them as much as possible, and classes of bugs found by static code scanning cause them to be adopted sprinkled through the rest of the code. Our C++ software is more stable than it has ever been because of it. Meanwhile, throwing everything away and rewriting it from scratch in another language has never been an option for any of those projects. Furthermore, even when there has been interest and buy-in to incrementally move to Rust in principle, in practice most of the time we evaluate using Rust for new features, the amount of existing code it must touch and the difficulty integrating Rust and C++ meant that we usually ended up using C++ instead. If features of Circle C++ were standardized, or at least stabilized with wider support, we would certainly start adopting them as well.
- School-Cotton 2y agoFor new projects on mainstream architectures that don't have to depend on legacy C++ baggage, Rust is great (and, I think, practically always the better choice). But, realistically, C++ will survive for as long as global technological civilization does. There are still people out there maintaining Fortran codebases. (also, IDK if you already realized this, but it's funny that the person you're replying to is one of the most famous Rust boosters out there, in fact probably the most famous, at least on HN).
- steveklabnik 2y agoI have realized this. Sean and I have talked about it. I became a Rust fan because of its innovations in the space. That its innovations may spread elsewhere is a good thing, not a bad thing. If a language comes along that speaks to me more than Rust does, I’ll switch to that. I’m not a partisan, even if it may feel that way from the outside.
- pjmlp 2y agoIndeed, even if Rust disappeared tomorrow, I would assert that its biggest contribution has been to make affine type systems more understanable in mainstream, to the point several languages, including a few with automatic memory management, are adding such concepts to their type systems without having their communities running away in horror, rather embracing the experiment.
- jmull 2y ago> It seems to me like we already have a lower-overhead approach ... Rust Rewriting all the existing C++ code in Rust is extremely high-cost. Practically speaking, that means it won't happen in many, many cases. I think we want to find a more efficient way to achieve memory safety in C++. Not to mention, Rust's safety model isn't that great. It does memory safety, which is good, but it's overly restrictive, disallowing various safe patterns. I suspect there are better safe alternatives out there for most cases, or at least could be. It would make sense to consider the alternatives before anyone rewrites something in Rust.
- steveklabnik 2y agoFolks who want to propose alternatives should do so! Right now, you’ve only got the two: profiles and Safe C++. There are also two that aren’t proposals. It have a semblance of a plan: “graft Hylo semantics instead of Rust semantics” and “scpptool.” Realistically, unless something else concrete and not “could be” is found at the eleventh hour, this is the reality of the possible choices.
- jmull 2y agoDon't forget the comment above proposes another alternative, "rewrite it in Rust". The problem with such a proposal is that the cost is impossibly high for many, many cases. Effectively, across the entire existing C++ code base, you get "X% rewrite it in Rust plus (1-X)% do nothing at all", where X is probably a lot closer to 0 than 1. If your goal is to address as many vulnerabilities as possible, you might want to look for a better plan. I don't have a ready plan, but the general approach of incrementally improving the safety of existing C++ seems likely to be more effective than rewrites to me -- it could let the X in my formula move a lot closer to 1. Possibly one of the existing mechanisms for this is already better than "RIIR". Edit, I meant to add: For many, many things it's not the eleventh hour. For a lot of existing C++ code, no one has reached a final decision point. Many haven't really started at all and are at the 0th hour.
- zozbot234 2y ago> It does memory safety, which is good, but it's overly restrictive, disallowing various safe patterns The "safe" patterns Rust disallows tend to not account for safe modularity - as in, they impose complex, hard-to-verify requirements on outside code if "safety" is to be preserved. This kind of thing is essentially what the "unsafe" feature in Rust is intended to address.
- SubjectToChange 2y ago>...I hope the committee ends up making the right call here. WG21 hasn't been able to solve the restrict type qualifier, or make a better alternative, in over twenty years. IMO, hoping that WG21 adequately solves Safe C++ is nothing more than wishful thinking, to put it charitably.
- steveklabnik 2y agoI am intimately familiar with the dysfunctions of various language committees. I never said it would be easy, or probable. But I’m also the kind who hopes for the best.
- OskarS 2y agoYeah, this one is so weird. You've been able to do that forever in C, and virtually all big compilers have this keyword in C++ as well, just named __restrict. Why is it so hard to get into the standard, at least for pointers? I can imagine that there are complex semantics with regards to references that are tricky to get right, but can't we at least have "'restrict" can only be used on raw pointer types, and it means the same thing as it does in C"?
- myworkinisgood 2y ago[flagged]
- pjmlp 2y agoGiven how C++0x concepts, C++20 contracts, ABI discussion went down, where key people involved on those processes left to other programming language communities, not sure if the right call will be done in the end. This is a very political subject, and WG21 doesn't have a core team, rather everything goes through votes. It suffices to have the wrong count in the room when it is time to vote.
- thadt 2y agoI have a long standing debate with a friend about whether the future of C++ will be evolution or extinction. Safe C++ looks excellent - its adoption would go a long way toward validating his steadfast belief that C++ can evolve to keep up with the world.
- o11c 2y ago"No mutable aliases" is a mistake; it prevents many useful programs. Now that virtual address space is cheap, it's possible to recompile C (or presumably C++) with a fully-safe runtime (requiring annotation only around nasty things like `union sigval`), but this is an ABI break and has nontrivial overhead (note that AddressSanitizers has ~2x overhead and only catches some optimistic cases) unless you mandate additional annotation.
- murderfs 2y agovirtual address space is cheap, but changing it is massively expensive. If you have to do a TLB shootdown on every free, you're likely going to have worse performance than just using ASan.
- o11c 2y agoDealing with malloc/free is trivial and cheap - just give every allocated object a couple of reference counts. The hard part is figuring out which words of memory should be treated as pointers, so that you know when to alter the reference counts. Most C programs don't rely on all the weird guarantees that C mandates (relying on asm, which is also problematic, is probably more common), but for the ones that do it is quite problematic.
- akira2501 2y ago> just give every allocated object a couple of reference counts. Works great with a single thread.
- o11c 2y agoMulti-threaded refcounts aren't actually that hard? There's overhead (depending on how much you're willing to annotate it and how much you can infer), but the only "hard" thing is the race between accessing a field and and changing the refcount of the object it points to, and [even ignoring alternative CAS approaches] that's easy enough if you control the allocator (do not return memory to the OS until all running threads have checked in). Note that, in contrast the the common refcount approach, it's probably better to introduce a "this is in use; crash on free" flag to significantly reduce the overhead.
- SubjectToChange 2y agoAt this point I'm wondering if the purpose of safety profiles is simply to serve as a distraction. In other words, safety profiles are just something people can point to when the topic of memory safety comes up, that’s it. The objectives of the initiative always seemed hopelessly optimistic, if not absurd. In particular, I don't understand why littering a codebase with auto, const, constexpr, inline, [[nodiscard]], noexcept, etc is wonderful, yet lifetime annotations are somehow an intolerable tyranny.
- ameliaquining 2y agoI think maybe it's because lifetime annotations can get arbitrarily complicated. If you look at enough Rust code you'll definitely see some function signatures that make your head hurt, even if they're vastly outnumbered by simple ones. A guarantee that the comprehension complexity of that part of your code will always be below some low ceiling is tempting.
- whimsicalism 2y agoRust has nothing on template meta programming and the type signatures you get there, though
- nickitolas 2y agoNot to mention the error messages when you get something slightly wrong
- crest 2y agoGive the proc macro fans a little more time...
- jerf 2y agoI understand the point you are making, but C++ templates really are a uniquely disastrous programming model. They can be used to pull off neat tricks, but the way those neat tricks are done is terrible.
- loeg 2y agoSection 6 seems to propose adding essentially every Rust feature to C++? Am I reading that right? Why would someone use this new proposed C++-with-Rust-annotations in place of just Rust?
- steveklabnik 2y agoHere’s the actual proposal: https://safecpp.org/draft.html https://safecpp.org/draft.html It explains its own motivation.
- ijustlovemath 2y agoBecause the millions of lines of existing C++ aren't going anywhere. You need transition capability if you're ever gonna see widespread adoption. See: C++'s own adoption story; transpiling into C to get wider adoption into existing codebases.
- SubjectToChange 2y ago>Why would someone use this new proposed C++-with-Rust-annotations in place of just Rust? Simply making C++ compilers compatible with one another is a constant struggle. Making Rust work well with existing C++ code is even more difficult. Thus, it is far easier to make something like Clang understand and compile C++-specific annotations alongside legacy C++ code than making rustc understand C++ types. Moreover, teams of C++ programmers will have an easier time writing annotated C++ than they would learning an entirely new language. And it's important to recognize how deeply entrenched C++ is in many areas, especially when you consider things like OpenMP, OpenACC, CUDA, HIP/ROCm, Kokkos, etc etc etc.
- leni536 2y agoFeatures C++ has that Rust doesn't: * template specialisations * function overloading * I believe const generics is still not there in Rust, or its necessarily more restricted. In general metaprogramming facilities are more expressive in C++, with different other tradeoffs to Rust. But the tradeoffs don't include memory safety.
- ynik 2y ago
- favorited 2y agoI know Sean said on Twitter that he probably won't submit this to WG21, but I wish he would... It is a fantastic rebuttal of certain individual's continued hand-waving about how C++ is safe enough as-is.
- bfrog 2y agoThis seems to be a common theme with many c++ developers honestly.
- saagarjha 2y agoSome of them are unfortunately on language committees.
- OvbiousError 2y agoMost C++ devs don't care that much either way I'd say, it's a vocal minority that does. I really don't understand the nay-sayers though, been a C++ dev for over 15 years, I'd give an arm and a leg for 1. faster language evolution (cries in pattern matching) and 2. a way to enforce safe code. Having to use std::variant when I want to use a sum type in 2024 is just so backwards it's hard to express. Still love the language though :p
- pjmlp 2y agoC++ became my favourite language after Object Pascal, as it provided similar safety levels, added with the portability. I never been that big into C, although I do know it relatively well, as much as anyone can claim to do so, because it is a key language in anything UNIX/POSIX and Windows anyway. One of the appealing things back then were the C++ frameworks that were provided alongside C++ compilers, pre-ISO C++98, all of them with more security consideration than what ended up landing on the standard library, e.g. bounds checking by default on collection types. Nowadays I rather spend my time in other languages, and reach out to C++ on a per-need basis, as other language communities take the security discussion more seriously. However, likewise I still love the language itself, and is one of those that I usually reach for in side projects, where I can freely turn to 100% all the safety features available to me, without the usual drama from some C++ circles.
- ameliaquining 2y agoThese considerations all seem so self-evident that I can't imagine the architects of Safety Profiles weren't aware of them; they are basically just the statement of the problem. And yet these smart people presumably thought they had some kind of solution to them. Why did they think that? What did this solution look like? I would be very interested to read more context on this.
- steveklabnik 2y agoAs always with different designs from smart people, it’s about priorities. The profiles proposal focuses on a lack of annotations (I think there’s reasonable criticism that this isn’t achieved by it though…), and believing they can get 80% of the benefit for 20% of the effort (at least conceptually, obviously not those exact numbers). They aren’t shooting for full memory safety. The Safe C++ proposal asks “how do we achieve 100% memory safety by default?”. And then asks what is needed to achieve that goal.
- ameliaquining 2y agoWhat's with the "this model detects all possible errors" quote at the beginning of the post, then?
- steveklabnik 2y agoThat’s a claim about dangling pointers and ownership. Profiles do not solve aliasing or concurrency, as two examples of things that Safe C++ does that are important for memory safety.
- ameliaquining 2y agoConcurrency, sure, I can see thinking of that as a separate thing (as some people from Google have advocated for). But aliasing isn't a memory safety violation, it's a cause of memory safety violations (and other kinds of bugs besides). The first example from the linked post is straightforwardly a dangling pointer dereference, and I don't understand how the people behind safety profiles can claim that it's out of scope just because it involves aliasing. Did they say something like "this assumes your code follows these non-machine-checkable aliasing rules, if it doesn't then all bets are off"?
- zahlman 2y agoWhat actually is this circle-lang site, and who runs it? The main page seems to just redirect to example.com, and I don't recognize the name of the author.
- steveklabnik 2y agoCircle is a C++ compiler by Sean Baxter, with various extensions. One of those is an implementation of the Safe C++ proposal I’ve linked downthread.
- crote 2y agoDoes the Circle compiler see any real-world use? I keep hearing about it, but it seems like it is a one-person project which hasn't seen significant activity in about a year. On paper it does sound quite promising, but looking at the Github repo I can't help but shake the feeling that it is more talk than action. It seems to have basically been abandoned before it ever saw any adoption?
- pjmlp 2y agoAt least Circle is real, something that one can download, validate its ideas, what works, what does not. Most of the profiles being argued for C++ only exist in PDF form, there isn't a single C++ compiler where you can validate those ideas, but trust the authors, the ideas will certainly work once implemented.
- steveklabnik 2y agoIt’s not open source. The GitHub activity is purely for documentation. I don’t know about real world adoption, nor do I think it’s really about what I’m saying. The proposal was made public a few weeks ago. There hasn’t been much time for real world projects to adopt it, if that were even the goal. The point is that it does exist today, and you can try it out. It’s more than just a design on paper.
- catskul2 2y agoI'm surprised you've not heard of the author (Sean Baxter). He's pretty well known among people who are interested in c++ standards proposals. He single handedly wrote his own C++ front-end and then proceeded to implement a butt load of extensions which other members of the committees poo-pood as being to hard to implement in the compiler. Every couple of weeks he implements something new. He's a real joy to follow.
- prophesi 2y agoFor those without a dark mode extension: body { background-color: #1f1f1f; color: #efefef; } .sourceCode { background-color: #3f3f3f; }
- CJefferson 2y agoThis article is really good, and covers many important issues. There were many similar issues when it came to the earlier attempts to add concepts to C++ (which would improve template dispatch), although the outcome was more about improving C++ programmer's lives, not safety. It turned out trying to encapsulate all the things C++ functions, even in the standard library, as a list of concepts, was basically impossible. There are so many little corner-cases in C++ which need representing as a concept, the list of 'concepts' a function needed often ended up being longer than the function itself.
- j16sdiz 2y ago> A C++ compiler can infer nothing about aliasing from a function declaration. True. but you don't solely rely on the declaration, do you? lots of power comes from static analysis.
- steveklabnik 2y agoIt’s important to only rely on the declaration, for a few reasons. One of the simpler ones is that the body may be in another translation unit.
- seanbax 2y agoYou do solely rely on the declaration. From P3465: "why this is a scalable compile-time solution, because it requires only function-local analysis" Profiles uses local analysis, as does borrow checking. Whole program analysis is something you don't want to mess with.
- mimd 2y agoI'm confused over lines such as "Profiles have to reject pointer arithmetic, because there’s no static analysis protection against indexing past the end of the allocation." Can't frama-c/etc do that? Additionally, section 2.3 is narrower than what is implied by the words "safe" and "out-of-contract" and is more concerned with what C/C++ call "undefined behavior" requirements than contract correctness. Ie. An integer which is defined to wrap overflows and violates the requirement of the function contract, which I can cause in a safe release build rust.
- bjornsing 2y agoHow is it supposed to do that (in the general case)? If I write a C++ program that will index out of bounds iif the Riemann hypothesis is true, then frama-c would have to win the millennium prize to do its job. I bet it can’t.
- bluGill 2y agoOften when I look into questions like this I discover the general case is impossible, but simple hysterics can get 99.999% of the cases and so I can get almost all the benefit even though some rare cases are missed.
- zozbot234 2y agoMy own semi-random guess is that "simple hysterics" is indeed how a vast majority (if perhaps not quite 99.999%) of C/C++ devs approaches the code correctness problem - which is why safety mechanisms like the one proposed by OP may in fact be urgently needed. Simple heuristics are likely to be significantly more worthwhile, if appropriately chosen.
- bluGill 2y agoC++ for sure needs better safety mechanisms. And I don't know the exact number of issues simple heuristics can catch.
- 2y ago
- account42 2y agoThe assumption here seems to be that the compiler/analyzer is only able to look at one function at a time. This makes no sense. Safety is a whole-program concern and you should analyze the whole program to check it. If anything as simple as the following needs lifetime annotations then your proposed solution will not be used by anyone: const int& f4(std::map<int, int>& map, const int& key) { return map[key]; }
- simonask 2y agoWhole-program analysis is not tractable (i.e., not scalable), and Rust has already proven that function signatures are enough, and does actually scale. The analysis can be performed locally at each call site, and doesn't have to recurse into callees. Your function would look like this in Rust: fn f4<'a>(map: &'a Map<i32, i32>, key: &i32) -> &'a i32 { ... } You don't need much more than a superficial understanding of Rust's lifetime syntax to understand what's going on here, and you have much more information about the function.
- jerf 2y ago"Whole-program analysis is not tractable (i.e., not scalable)," The search term for those who'd like to follow up is "Superoptimization", which is one of the perennial ideas that programmers get that will Change the World if it is "just" implemented and "why hasn't anyone else done it I guess maybe they're just stupid", except it turns out to not work in practice. In a nutshell, the complexity classes involved just get too high. (An interesting question I have is whether a language could be designed from the get-go to work with some useful subset of superoptimizations, but unfortunately, it's really hard to answer such questions when the bare minimum to have a good chance of success is 30 years of fairly specific experience before one even really stands a chance, and by then that's very unlikely to be what that person wants to work on.)
- gpderetta 2y agoSomething I would like to know is how much lifetime annotation you can infer (recursively) from the function implementation itself. Compiler driven, IDE integrated, automatic annotation would be a good tool to have. Some amount of non-local inference might also be possible for templated C++ code that already lack a proper separate compilation story.
- randomNumber7 2y agoThis is a great article and shows why its so hard to program in C++. When you do not deeply understand the reasons why those examples behave as they do, your code is potentially dangerous.
- rurban 2y agoAdditionally I still cannot understand why they didn't make iterators safe from the very beginning. In the alias examples some iterators must alias and some not. With safe iterators the checks would be trivial, as just the base pointers need to be compared. This could be done even at compile-time, when all iterators bases are known at compile-time. Their argument then was that iterators are just simple pointers, not a struct of two values base + cur. You don't want to pass two values in two registers, or even on the stack. Ok, but then call them iterators, call them mere pointers. With safe iterators, you could even add the end or size, and don't need to pass begin() and end() to a function to iterate over a container or range. Same for ranges. A iterator should have just have been a range (with a base), so all checks could be done safely, the API would look sane, and the calls could be optimized for some values to be known at compile-time. Now we have the unsafe iterators, with the aliasing mess, plus ranges, which are still unsafe and ill-designed. Thanksfully I'm not in the library working group, because I would have had heart attacks long time ago over their incompetence. My CTL (the STL in C) uses safe iterators, and is still comparable in performance and size to C++ containers. Wrong aliasing and API usage is detected, in many cases also at compile-time.
- sirwhinesalot 2y agoWe're talking about a commitee that still releases "safety improving" constructs like std::span without any bounds checking. Don't think about it too much.
- jcelerier 2y ago> My CTL (the STL in C) uses safe iterators, and is still comparable in performance and size to C++ containers I wonder, what's "comparable" there ? Because for instance MSVC, libstdc++ and libc++ supports some kind of safe iterators but they are definitely not useable for production due to the heavy performance cost incurred.
- munificent 2y agoThe C++ committee and standard library folks are in a hard spot. They have two goals: 1. Make primitives in the language as safe as they can. 2. Be as fast as corresponding completely unsafe C code. These goals are obviously in opposition. Sometimes, if you're lucky, you can improve safety completely at compile time and after the safety is proven, the compiler eliminates everything with no overhead. But often you can't. And when you can't, C++ folks tend to prioritize 2 over 1. You could definitely argue that that's the wrong choice. At the same time, that choice is arguably the soul of C++. Making a different choice there would fundamentally change the identity of the language. But I suspect that the larger issue here is cultural. Every organization has some foundational experiences that help define the group's identity and culture. For C++, the fact that the language was able to succeed at all instead of withering away like so many other C competitors did is because it ruthlessly prioritized performance and C compatibility over all other factors. Back in the early days of C++, C programmers wouldn't sacrifice an ounce of performance to get onto a "better" language. Their identity as close-to-the-metal programmers was based in part on being able to squeeze more out of a CPU than anyone else could. And, certainly, at the time, that really was valuable when computers were three orders of magnitude slower than they are today. That culture still pervades C++ where everyone is afraid of a performance death of a thousand cuts. So the language has sort of wedged itself into an untenable space where it refuses to be any slower than completely guardrail-less machine code, but where it's also trying to be safer. I suspect that long-term, it's an evolutionary dead end. Given the state of hardware (fast) and computer security failures (catastrophically harmful), it's worth paying some amount of runtime cost for safer languages. If you need to pay an extra buck or two for a slightly faster chip, but you don't leak national security secrets and go to jail, or leak personal health information and get sued for millions... buy the damn chip.
- MathMonkeyMan 2y agoWhy is `f3` safe? My thought (which is apparently wrong) is that the `const int& x` refers to memory that might be freed during `vector::push_back`. Then, when we go to construct the new element that is a copy of `x`, it might be invalid to read `x`. No? Is this related to how a reference-to-const on the stack can extend the lifetime of a temporary to which it's bound? I didn't think that function parameters had this property (i.e. an implicit copy).
- deleted 2y ago[deleted]
- seanbax 2y agoIf the vector has to be resized in push_back, the implementation copy-constructs a new object from x. It resizes the buffer. Then it move-constructs the copy into the buffer. The cost is only a move construct per resize... So it's on the order of log2(capacity). Very efficient. But don't get used to it, because there are plenty of other C++ libraries that will break under aliasing.
- embe42 2y agoI think the implementation in C++ does not do realloc on push_back, but allocates new memory, creates the new element and only then deallocates it. I believe the reason f3 is safe is that the standard says that the iterators/references are invalidated after push_back – so push_back needs to be carefully written to accept aliasing pointers. I am pretty sure if I were writing my own push_back it would do something like "reserve(size() + 1), copy element into the new place", and it would have different aliasing requirements... (For me this is a good example of how subtle such things are)
- MathMonkeyMan 2y ago> allocates new memory, creates the new element and only then deallocates it. Ah, I'll have to check the standard. Thanks.
- tialaramex 2y ago
- WalterBright 2y ago> What are sort’s preconditions? 1. The first and last iterators must point at elements from the same container. 2. first must not indicate an element that appears after last. 3. first and last may not be dangling iterators. This is a fundamental problem in C++ where a range is specified by the starting point and the ending point. This is because iterators in C++ are abstractions of a pointer. D took a different approach. A range in D is an abstraction of an array. An array is specified by its starting point and its length. This inherently solves points one and two (not sure about three). Sort then has a prototype of: Range sort(Range);