3 ms·
The author's examples are contrived. First, they do gratuitous allocation (e.g. `char* foo = strdup ("Hi");` followed by explaining that they have to allocate
by gumby 4y ago
The author's examples are contrived.
First, they do gratuitous allocation (e.g. `char* foo = strdup ("Hi");` followed by explaining that they have to allocate again because of their use of *foo. No need for the first copy and nobody would write the code that way.
Second they seem not to realize you can allocate straight into your destination memory (i.e. 'emplace'). So again, they are complaining about something nobody would ever do.
Then they make assertions about runtime behavior of C++ code that could easily be disproven by simply looking at what the compiler does! The C++ compiler can perform optimizations Rust cannot (perhaps can in the future) such as allocating directly into the caller's stack frame so that the "move" never happens at runtime at all!
I stopped reading at this point. It's a shame, as the author also refers to legitimate issues with C++'s memory model (e.g. a reference can point to invalid memory in certain multithreaded code) which are partially mitigated by Rust's memory model.
Rust has its strengths and weaknesses vs C++, but this article doesn't appear to really get to them.
- deleted 4y ago[deleted]
- ninkendo 4y agoThe gratuitous allocation is what would need to take place if C++ didn’t have move semantics. The whole point of that part of the article is to set the background for why C++11 move semantics were added, and what problem they solved (mainly that if C++ only allows copy and destruct, there’s no opportunity to avoid extra allocations/deletions when doing something like sorting a vector<string>.) Also “emplace” was added to C++11 and was only possible due to the new move semantics (aka rvalue references.) Anyhow, after explaining the background, the article goes on to critique some of the more annoying aspects of C++11’s move semantics, namely that the destructor is still called on the moved-from object (and thus you have to arrange for it to happen gracefully in your move-constructor’s logic), and that C++ lets you continue using a moved value and the compiler won’t/can’t complain to you, e.g. // given void foo(std::string &&s); auto s = std::string("Hello"); foo(std::move(s)); std::count << s << std::endl; // U.B.. But the compiler won’t complain! I have to say, the “considered harmful” monicker may actually be warranted here. When I was reading about move semantics back when it was still called C++0x, I was actually shocked to learn that there’s nothing the compiler could do to stop you from just continuing to use a reference that was moved from. That could have been one of the best benefits of the new semantics, and they just swept it under the rug and called it “undefined behavior”.
- tomjakubowski 4y agoUsing a moved-from std::string value, or one of any standard library type, isn't undefined behavior.
- ninkendo 4y ago(/me does some quick googling) I guess it’s in an “unspecified” state after move, which I suppose is different from undefined. Still doesn’t take away from my main point which is that C++ has no problem allowing you to use a reference that has been moved from (which I’d wager is a mistake in very nearly 100% of cases.)
- AnimalMuppet 4y agoIsn't that the difference between move and copy? Copy means the original is still valid; move means it isn't.
- ninkendo 4y agoWell, that’s just the rub: It’s up to the implementor of a given type to decide what happens to an object that’s been moved-from. They could do something silly like make a `print(std::string&&)` function which doesn’t actually do anything to the passed-in string, just prints it, but requires callers to `std::move` the arguments, even if it’s not actually moving anything. To C++, there’s no such thing as “moving” per se, there’s just “rvalue references”, and a standard library macro called “std::move” which is really just a static_cast to an rvalue reference. The compiler doesn’t mind if you continue to use something after casting it via std::move. It’s all rather disappointing, really (although I can understand why they did it… backwards compatibility is important in the C++ world.)
- AnimalMuppet 4y ago> the destructor is still called on the moved-from object Wait, what? If I have a class with a pointer to some allocated memory, then the constructor should allocate the memory, the destructor should free it, copy should allocate an equal-sized amount of memory, and move should just give the destination the pointer (meaning that the destination now owns the allocated block, the original does not). Calling the destructor on the original means that the destination's block of memory is freed (unless you null the origin's pointer as part of the move). I've never actually written a move that I recall, but this behavior is very surprising to me.
- pcwalton 4y ago> It's a shame, as the author also refers to legitimate issues with C++'s memory model (e.g. a reference can point to invalid memory in certain multithreaded code) which are partially mitigated by Rust's memory model. This issue is not partially mitigated by Rust's memory model; it is fully solved, because Rust is memory safe.
- eklitzke 4y agoI strongly agree. This post is SO MANY WORDS basically to complain about the fact that the state of a moved-from object is partially unspecified (i.e. the object has to be in a valid state and destructible, but what that state is is not necessarily guaranteed by the language). Obviously this behavior is a little weird when you first encounter it. A lot of C++ developers find it weird as well, and I'm sure a lot of C++ developers have made mistakes around this at one time or another. However, it's not nearly as bad as the article makes out. For one thing, clangd/clang-tidy will emit warnings if you use a moved-from object in an unsafe way, e.g.: some_vector.emplace_back(std::move(foo)); foo.whatever(); // <-- clang-tidy will warn about this Using these kinds of static analysis tools is pretty much essential in any professional C++ role. Could you argue that it would be better if this was a language feature instead of something that you need a static analyzer for? Of course, but in practice everyone is using these tools anyway so it's not a big deal. Additionally the C++ semantics are sometimes really useful. As a simplified example, I have some code at work that looks something like this (simplified here, but this shows the general idea): struct CounterData { // Threads call this method very frequently, say thousands of times per second void AddCounter(std::string_view key, int val) { absl::MutexLock lk(&mut); // ALMOST NEVER CONTENDED counters[key] += val; } absl::flat_hash_map<std::string, int> counters; absl::Mutex mut; }; // Thread-local instance of counter_data static thread_local CounterData counter_data; // Main thread calls this infrequently, say once a second absl::flat_hash_map<std::string, int> AggregateCounters() { std::vector<absl::flat_hash_map<std::string, int>> all_counters; // Assume it's possible to enumerate threads and iterate over thread local counters, // this is not a difficult abstraction to build. all_counters.reserve(num_threads); for (CounterData &data : all_thread_local_counters) { absl::MutexLock lk(&data.mut); all_counters.emplace_back(std::move(data.counters)); } absl::flat_hash_map<std::string, int> aggregate; for (const auto &map : all_counters) { for (const auto &[k, v] : map) { aggregate[k] += v; } } return aggregate; } Again, this is a simplified example. But the point of this code is that it minimizes the time spent in the critical section where each per-thread CounterData is locked by the main thread. Normally calls to AddCounter() will be uncontended and the lock acquisition will be nearly free. The only time the lock is contended is if an AddCounter() call happens at the same time as a call by the main thread to AggregateCounters(). However, AggregateCounters() holds these locks for really short periods of time, because it can acquire the lock, move the absl::flat_hash_map, and then release the lock. The move just updates a few pointers and afterwards the map is in a default initialized state, so it's perfectly OK for the threads to call AddCounter() immediately afterwards, even though the object is in a moved-from state. And AggregateCounters() does all the expensive work (iteration and summing) without needing to hold any locks. You might object: how do you know the state of an absl::flat_hash_map after moving it? It's a reasonable thing to ask but in practice it's really easy to understand. Pretty much anyone writing a custom move constructor is going to do something reasonable, like move pointers to the new object and probably reset the original pointers to nullptr. Since the object needs to be in a valid state after move, this means that things like integer length/capacity fields and whatnot will also need to be reset to zero afterwards, since if they weren't the object wouldn't be in a usable state. And if you have any questions about this, you just look at the code. But really 99.99% of the time the author is going to write their move constructor in a sane way where you can guess the behavior from a few basic principles. The original post also specifically complains that std::string is weird because if the string is large enough that it allocates then the string will probably be in an empty state after the call to std::move, and if the string is small enough that SSO applies it will probably be in the same state afterwards, and the standard doesn't guarantee anything. Fair enough, but this just means you need to assume that you don't know the string state after a move, and you can't read from a moved-from string. Again, clang-tidy and clangd will warn you if you try to use a string this way.
- thecodedmessage 4y agoAuthor here! My "example" is showing an equivalent to what the C++ compiler actually outputs, inlining the `std::string` abstraction, given the input code, which in this context was C++03, and before emplace. But emplace doesn't save you here! Emplace doesn't save on heap allocations over a `strdup`, if you're emplacing something from a string literal like this. Doing: ``` vec.emplace_back("here's a string"); ``` Does indeed do an allocation for the string. It has to, because every `std::string` must manage a heap allocation (modulo the small string optimization which is a nitpick). The string literal is in the `text` section of the binary and can't be the backing for the `std::string` object, which must be in read-write memory and on the heap. So the `strdup` is correct as an equivalent to what the C++ compiler would output with `std::string` inlined for the example code it covered. Also, the freeing of the empty object with move semantics is NOT always optimized out, not even close. It can't be, not when those calls can cross a library boundary or be arbitrarily wonky. You write as if C++ has one optimizer. Rust shares an optimizer with one of the most popular C++ compilers. Implying Rust is somehow "behind" C++ on optimizations is just ill-informed.