▲ 5 r/cpp_questions
cppreference has a page with example code of the rule of 3/5. what is your opinion on it? i have seen different implementations of it (kinda irritating that everyone seems to have their own spin/implementation of it) so im not sure what advantages or drawbacks this particular implementation has. skimming over it, it seems very elegant. I'll also try to explain each implementaion just to make sure I understand what they are doing.
- constructor: copies a string into dynamically allocated memory based on a char* passed in the constructor (let's call this "resource")
- copy constructor: just uses the constructor with the resource of the passed instance
- destructor: deallocates the resource
these are the same for r3 & r5
rule of 3:
- copy assignment: uses std::swap with the resource of a newly constructed instance initialized with the passed instance (old resource will be deallocated because it's now inside the locally created instance whose lifetime ends inside the copy assignment block and its destructor is called at the end)
rule of 5:
- copy assignment: uses move assignment by assigning itself to a temporary expiring (r-value) instance initialized with the passed instance. the old resource will be deallocated since the move assignment operator swapped it with the expiring instance's resource, which means the destructor of the expiring instance will deallocate the resource.
- move constructor: sets its own resource with std::exchange with the resource of the passed instance, setting the other's resource to nullptr
- move assignment: uses std::swap on the passed instance. presumably, the old resource will be deallocated when the passed instance goes out of scope and its destructor is called.
without thinking too much, i'd just default to this whenever rule of 3/5 is something i have to deal with.
u/HeeTrouse51847 — 16 days ago