175 points · by awesomekling · 7y ago · 188 comments
C++ lack of modules and package management on the other hand is a huge PITA and I'm not optimistic either of those bolted on so late in to the language lifecycle will provide a useful solution.
It's a pity D took it too far in the other direction with GC and runtime - I really could use a C with classes and modules.
[1]: https://dlang.org/blog/the-d-and-c-series/#betterC [2]: https://theartofmachinery.com/2019/04/05/d_as_c_replacement....
Some example of what can be done with it https://gitlab.com/xadix/xonan
It is kind of like gentoo portage or nix pkg and can be used to manage your tool chain also
What exactly does "modules" mean to you? JS modules, Ruby modules, Java modules, Python modules? Those are substantially different ideas. C++ namespaces are Ruby modules, sans inheritance and runtime representation.
> package management
Does every language now require its own bespoke package management? npm, gem, pip, CPAN, OPAM, composer, maven, ivy, NuGet, Cabal, Cargo, CocoaPods, Quicklisp, LuaRocks, CTAN, Anaconda, etc.
Get every OS to agree on an universal package manager and then we may get rid of language specific ones that work across all OSes.
An with the GUI going into Web it then just installs into some kind of Docker image anyway.
Here's a couple of interesting examples of failure modes -Wlifetime can detect on godbolt[2][3].
I watched a video [5] a while back on the Guidelines Support Library (GSL) [4] and it seemed like a really interesting concept. I think it's a valuable idea and I'd love to see popular C++ projects leveraging it.
I'm a card-carrying RESF member† (but have a day job w/mostly C++). Don't RIIR for one thing, RIIR to get all the things. Cargo is the sleeper hit of Rust. Hygienic macros and more!
[1] https://github.com/isocpp/CppCoreGuidelines/blob/master/docs...
[2] https://godbolt.org/z/dymV_C
[3] https://godbolt.org/z/_midIP
[4] http://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#...
[5] CppCon 2017: Kate Gregory “10 Core Guidelines You Need to Start Using Now” https://www.youtube.com/watch?v=XkDEzfpdcSg
† Rust Evangelism Strike Force -- maybe we really should have cards
https://gitlab.gnome.org/GNOME/librsvg/issues/456
Apparently, GObject Introspection doesn't even work in Rust, yet it is expected to be a perfectly valid replacement:
https://github.com/gtk-rs/gir-files/issues/35
Please don't be like these people! Keep the stable software we have, and maybe write new software in Rust.
> Please don't be like these people! Keep the stable software we have, and maybe write new software in Rust.
I say: spend your time how you see fit. I love Open Source software, I love GNU/linux and GNOME. But IMO it's always been about scratching an itch first and commitment to a cause second.
As the maintainers of the software shouldn't they have the prerogative to maintain the software in the best way they see fit?
Bugs happen while refactoring, regardless of how the refactoring is done.
Gtk support on OS X has been absymal, forever. If this helps that, I'm all for it, thanks.
The value these kinds of smart Cpp/Compiler features comes from the ability to eliminate some instances of bugs.
Which is great, and all, but I don't see that all of the great masses of Cpp code and libraries would be rewritten or annotated to use these new features.
Which will sadly leave the impact of these developments particial.
> I don't see that all of the great masses of Cpp code and libraries would be rewritten or annotated to use these new features.
It's much more likely and tractable that C++ libraries will be annotated than that they'll be rewritten from scratch in Rust.
But sure, it is somewhat of an uphill struggle. Still a worthy goal, as I don't think we will get rid of the many massively popular C++ softwares anytime soon.
That said, I like this push for more programmatic checks.
That's in all the Pascal-family languages - Pascal, Modula, Ada.
"Perhaps the future of software isn't "rewrite everything in Rust", but instead we end up annotating existing C/C++ with borrow checking information."
Trying to retrofit this to C++ runs into the problem that too often you're lying to the language to get something done. Like extracting a raw pointer to be sent to a system call. You have to break a lot of existing code to make this work. Which means a new safer C++ like language. There are about five of those to choose from, none of which are used much.
Rust was right to do a clean break. But then they just got too weird, with their own brand of functional programming and their own brand of a type system.
you mean like the gigabytes of rust code just put in unsafe {} blocks or doing panic! when they don't know what to do with the error ? :p
Microsoft's C/C++ annotations: https://docs.microsoft.com/en-us/visualstudio/code-quality/u...
Ada's ranges: https://en.wikibooks.org/wiki/Ada_Programming/Types/range
Fun stuff to learn about in theory, but, unless you're working at a place where formal verification is part of the culture, good luck selling these tools to upper management.
More resources discussed here: http://highscalability.com/blog/2018/9/19/how-do-you-explain...
C++ is fine, but most projects are riddled with ugly macros and #defines for features / platform specific code. Rust solves this in a fairly elegant way. Also, not having a package ecosystem in C/C++ is frustrating as hell.
Cargo was the thing that pushed me over the hump to learn rust instead of just opting for c++, and it has paid off.
It's not quite as ergonomic as go, but overall it has won me over and is my new favorite language. I'm excited to see how the story for rust plays out over the next 5 years :)
Cargo has gotten definitely better, but lack of support for binary libraries is a pain point.
Most binary C++ libraries I've dealt with either require you use the same compiler, or export a C interface through extern "C".
Rust doesn't really support shared objects from Rust to Rust at all, from what I can tell (caveat that I've never actually tried it). There's no stable ABI (https://github.com/rust-lang/rfcs/issues/600), and therefore the only way to go is via a C interface. So Rust is more or less in the same place, just with fewer compilers.
IMO it's time to accept C++ is a failed state, and move on. Luckily there are compatibility options to help you use C/C++ libraries in Rust.
With Rust, its entire ecosystem (however nascent) is subjected to the same strict rules. This is big plus when Rust eco-system matures functionality wise.
A somewhat related example is how Emacs was built to support introspective programming, where nearly anything can be inspected to provide a docstring. This is both invaluable when extending the editor and only possible because Emacs established conventions early on about documenting public objects. Though it isn't obligatory to document things, the audience Emacs appeals to seemed to keep doing so through force of momentum over the years. I find this momentum incredibly important to have.
The problem is you can't just shoehorn this way of thinking onto any arbitrary language/programming environment, because the issue of dependencies following whatever code annotations they have arises. For C++ it's hopeless to imagine we can expect these annotation benefits to be universal because using the language didn't obligate adding them in some way, so the vast majority of people didn't. The author mentions there aren't even any real-world codebases using them. Every corner of the system/language has to be designed from the beginning with annotation in mind.
I've been pining over the same issue as I'm trying to design a "living system" that supports user extension. I'm still wondering if I'm missing anything that could help with introspection, is not detrimental to user experience and can only be added in the nascent stage the project is in. Once all the conventions are in place, everything will have to be built on top of them no matter how imperfect they are.
To see what I mean, in the examples in the article, the author has to tell the compiler all sorts of things that are hard to infer. For example, the object comes into being in the “unconsumed” state (what if I instantiate it with a nullptr? Can I even do that?), and a prerequisite to dereferencing it is that it is “unconsumed”.
It is plausible that there would someday be a set(foo&&) method that had “unconsumed, consumed, unknown” as a prerequisite, and always brought the type into the “unconsumed” state.
In practice, you shouldn’t be spraying these annotations all over a code base. They should be in library methods that are reused frequently, so that you get a lot of static analysis benefit from a small number of manual annotations.
A moved from vector might get reused to store new things for example.
If you write a poor move constructor that doesn’t do this you will get exactly what you asked for. However the compiler has no way to know you half assed it and must support a legal valid case.
See this stack overflow: https://stackoverflow.com/questions/9168823/reusing-a-moved-...
To quote office space, “Your moved from object only needs to be destructible. But some people choose to allow more and we encourage that.”
>Unless otherwise specified, all standard library objects that have been moved from are placed in a valid but unspecified state. That is, only the functions without preconditions, such as the assignment operator, can be safely used on the object after it was moved from
[1]: https://en.cppreference.com/w/cpp/container/vector/vector
The default move constructor does not zero out the rhs. It simply does a std::move on each of the fields, which for all the primitive types is simply a copy, including for bare pointers. For example this:
struct Foo { int a; void* b; };
int main() {
Foo f{ 20, (void*) 0xBADBEEF };
Foo f2 = std::move(f);
printf("f[%d, %p], f2[%d, %p]\n", f.a, f.b, f2.a, f2.b);
return 0;
}
will print this:
f[20, 0xbadbeef], f2[20, 0xbadbeef]There is no active zero-ing or "empty" state at any point unless the specific class defines that its move does that. unique_ptr defines that get() will be nullptr after-move, for example, but that's something unique_ptr itself is specifically defining.
As far as I remember, move constructors/assignments must leave the moved-from object in a valid state - just that the standard doesn't say anything about what that state is for standard classes.
Also, I have seen code where some kind of "result" can be moved from an object and then re-generated from scratch with different inputs. In that case it was perfectly valid to use it after move. But that's nitpicking, anyways.
auto no_destroy = new MoveNoDestroy();
MoveNoDestroy* moved_into;
*moved_into = std::move(*no_destroy);
Wouldn't call the destructor of the moved from MoveNoDestroy.The actual semantic state of the object may not make sense.
http://pcwalton.github.io/2012/12/26/typestate-is-dead.html
Although to be fair, clang's version is a highly limited particular case of typestate, with one axis of state with three values, rather than a general heavyweight typestate mechanism.
That big ugly object that would get copied on function return -- just create it before the function call and pass it in as a reference! No copy required.
For example, how do you cleanly create a factory function? A pretty simple thing. You'd return a pointer to a dynamically allocated object? But how do you guarantee that the caller doesn't just discard that return value or doesn't forget to delete it? Also this forces dynamic allocation for that object and adds an indirection to access, even when the caller might not want that.
Move semantics allow you to either make your resource wrapping objects movable (so you return them "by value" as value semantics objects but they get moved) or to use something like std::unique_ptr to wrap the returned dynamically allocated object. The former has the advantage that it gives the caller complete flexibility where to store the object (ex. it can store it locally on the stack or as a member) and avoids a pointer indirection.
Similar issues exist for producing copyable but expensive to copy objects (ex. containers). Move semantics allows for a typesafe/clean way to return them from factory functions while not having to worry about lifetime and performance.
Believe me, I would dearly like to learn something new that can benefit me in my daily work. But unfortunately I can't make sense of your examples as they stand so it would be great if you could provide some example code to illustrate your point.
I do not know about your background or experience in C++ and you may very well have valid points (hence my request for code examples). However I get to read a lot of code of inexperienced programmers in my job who use && references and std::move "because that's how you do it in a modern way" and then run into crap like use after move and then wonder what the hell went wrong...
Most newer languages have realized that implicit copy semantics is usually a bad thing, and duplicating objects requires explicitly saying that you're duplicating them (such as calling a .clone() method). Of course, some types are value types, where copy is cheap and better than reference, but such mechanisms are opt-in. C++ automatically generates these mechanisms, and gives you nasty error messages when you opt-out of default copy.
Move semantics are almost always better, but in C++, with its historical baggage of opt-out-of-implicit-copy-semantics, it means that constructing move-only types requires a lot of excessive calls to std::move. Compilers do a good job of telling you when you put one too many calls to std::move in, but the code is definitely verbose compared to C++, to the point that it tends to strongly weigh against actually using C++'s ability to annotate move-only methods. Furthermore, without something like the mechanism in the blogpost here, compilers don't give any indication of API misuse, so you can't leverage move-only types to construct safe-by-construction APIs.
This is something I've been tripping over a lot recently, as I have a type system where calling most methods makes the original object unusable.
If move semantics were the default, we'd either get more use-after-frees or require the awkwardness of the borrow checker to have a semblance of sanity.
I don't mean to sound arrogant but if someone is writing C++ at a level where he/she does accidental copies then that's a very clear sign to me to stay the hell away from move semantics and other advanced features.
I personally find things being copied by default a nice feature. It's more consistent than "PODs by value, objects by reference" such as in Java.
Well; https://groups.google.com/a/chromium.org/forum/#!msg/chromiu...
This is not true. The rules are simple: rule of three, rule of five, or the recommended one, rule of zero [1]. If you define a copy constructor, the compiler won't generate a move constructor. If you define a move constructor explicitly, the compiler won't generate a copy constructor silently. You have total control over how the language behaves.
So in summary, either stick to the rule of 5 or the rule of zero and you won't be surprised. If you don't mind expensive copies, rule of 3 is sufficient.
[1] https://en.cppreference.com/w/cpp/language/rule_of_three
So? As far as I know this could be 1 year+ 20 repeats.
In contrast to your experience, I missed move semantics since the early 2000s. It’s not just to avoid copies.
How about the ability to avoid pointers, aliasing, and allocation. Move semantics afford more than just avoiding a copy.
That works thanks entirely to move semantics. Do you dispute the usefulness of such a container?
> That big ugly object that would get copied on function return -- just create it before the function call and pass it in as a reference! No copy required.
Or just return it without a std::move and it still won't be copied. In fact 'return std::move(any_local_value)' is not just silly it's bordering on wrong as it defeats some RVO optimizations (and returning a T&& of a local is actually wrong as it's returning a reference to a local). That's not what the purpose or use is of move semantics at all.
> Do you dispute the usefulness of such a container?
Sort of. I agree it can be useful in some cases but in reality the added value over vector<shared_ptr<SomeThing>> or just vector<SomeThingPtr> (both of which do not require move semantics) is way too small IMO to justify the butchering of the language with std::move and rvalue references.
At the end of the day to me std::move is like const_cast. It's a quick fix that you can use to sort out a situation, but you shouldn't be proud of it because if you require it, chances are your design is messed up in a more fundamental way and the actual fix is sorting that out.
Also uses move semantics. It's not _required_ here, no, but it highly benefits from it. Huge efficiency gain to avoid all the atomic refs & unrefs during resize.
> vector<SomeThingPtr>
This is error-prone and a leak risk. You just made the code buggy and worse, kinda like using const_cast.
> At the end of the day to me std::move is like const_cast. It's a quick fix that you can use to sort out a situation, but you shouldn't be proud of it because if you require it, chances are your design is messed up in a more fundamental way and the actual fix is sorting that out.
No it's pretty much the exact opposite. Avoiding std::move or insisting you don't need it is like scattering const_cast everywhere. You're avoiding a thing that helps you categorically avoid bugs (like unique_ptr does) in favor of just winging it and hoping for the best.
For example, if you have a class C containing a pointer P to some data, where C’s destructor frees that pointer:
- a shallow copy of object O would return an object O2, containing that same pointer P, and leave O unmodified.
- a move of O to O2 would (1) make O2 contain P, but also would update O to no longer have that pointer P (it has to make that change, as destructing O at a later time shouldn’t free P anymore)
(1) yes, an implementation could also copy the data or increase a reference count, or, possibly, a zillion different things without running into problems.
Widget::Widget(Widget&& w) {
this->ptr = w.ptr; // shallow copy
w.ptr = nullptr; // nullify the source
}RVO can often sort out your object return problem just fine. But lifetimes are more subtle. Sometime move semantics can significantly clean up your overall design.
All of eigen was originally based on template expressions, which are very complex. That technique / hack is not necessary if you move data structures. You no longer have to do elaborate work around to avoid copying temporaries.
AFAIK Eigen uses these scary template things to save RAM bandwidth.
When you write x=a+b+c for large vectors, lazy evaluation will produce code that sequentially loads a, b, c, computes the sum in a register, stores to x.
If you’ll use move semantics and temporary variables, the code will be compiled into auto tmp = a+b; x=tmp+c; This code computes the complete tmp variable, stores in RAM, then load again. For simple things like sum or component-wise multiplication of long vectors, RAM is way slower than ALUs.