Say I have an RAII class, instances of which should never be copied:
class Session {
public:
Session(); // Allocates a resource and sets generates a unique Session::id.
~Session(); // Frees the resource
Session(const Session&) = delete;
Session& operator = (Session&) = delete;
private:
std::uint32_t id;
}
Given that I can't allow copies, I'd like to allow moving, so I need to implement the move constructor and move-assignment operator but I'm not sure what I should do with Session::id of the moved instance.
I can either:
- Set it to some value known to be invalid (maybe change the type to a
signed int and use
-1as the invalid value) - Use something like
std::optionaland set it tostd::nulloptto invalidate it.
Which (if either) of those options is correct?
Since this can be done without
std::optionalby just sacrificing one value out of the 232 possibleids, I'd do likestd::string::nposand initialize a constant of the unsigned type youridhas with-1.Example:
Demo
An option would be to let
0be theinvalid_idif that would feel more natural in your case. You'd just have to initializeinvalid_idwith0and change the id counting toid(++id_counter).