16
Modern C++ — RAII
(green7ea.github.io)
Welcome to the main community in programming.dev! Feel free to post anything relating to programming here!
Cross posting is strongly encouraged in the instance. If you feel your post or another person's post makes sense in another community cross post into it.
Hope you enjoy the instance!
Rules
Follow the wormhole through a path of communities [email protected]
What I find interesting is that move semantics silently add something to C++ that did not exist before: invalid objects.
Before, if you created an object, you could design it so that it kept all invariants until it was destroyed. I'd even argue that it is the true core of OOP that you get data structures with guaranteed invariants - a vector or hash map or binary heap never ceases to guarantee its invariants.
But now, you can construct complex objects and then move their data away with std::move() .
What happens with the invariants of these objects?
According to cppreference:
I would expect this to be true of all types. An easy way to do this is to null an internal pointer, set an internal fd to a sentinel, etc and check for that when needed, but this could be an easy source of errors if someone's not paying attention.
Ideally it would be statically checked if a value is used after being moved, but that's just my Rust brain speaking.
Depends on the object what happens when they are moved from. Some objects are put into a valid moved from state (usually depends on if doing so is free or required anyway. For example to satisfy the invariant of the moved to unique pointer the moved from pointer needs to be set to nullptr in order to prevent the moved tos unique pointer being deleted from underneath it)
So what do you do with a file object?
Douno off the top of my head. To take a wild guess they might just wrap a file handle and give it s nice api? If that's what they do then moving from the file zeros out he handle for basically the same reason smart pointers set their internal pointer to nullptr, so they don't delete it (or close the file in this case) underneath the new object.