this post was submitted on 13 May 2024
4 points (61.1% liked)

C++

1761 readers
1 users here now

The center for all discussion and news regarding C++.

Rules

founded 1 year ago
MODERATORS
you are viewing a single comment's thread
view the rest of the comments
[โ€“] [email protected] 14 points 5 months ago (1 children)

That's very much the wrong lesson.

Simply taking std::string by value (as it is a memory management class created for that explicit purpose) would have solved the problem without kneecapping every class you make.

Better rules to take out if this than to delete all move and copy operators:

[โ€“] lysdexic 1 points 5 months ago* (last edited 5 months ago)

Simply taking std::string by value (as it is a memory management class created for that explicit purpose) would have solved the problem without kneecapping every class you make.

I think you are missing the whole point.

The blogger tried to make a point about how special member functions can be tricky to get right if you don't master them. In this case, the blogger even presents a concrete example of how the rule of 3/rule of 5 would fail to catch this issue. As the blogger was relying on the implicit special member functions to manage the life cycle of CheeseShop::clerkName and was oblivious to the possibility of copying values around, this resulted in the double free.

You can argue that you wouldn't have a problem if the string was used instead of a pointer to string, which is a point that the blogger indirectly does, but that would mean you'd be missing the root cause and missing the bigger picture, as you'd be trusting things to work by coincidence instead of actually knowing how they work.

The blogger also does a piss-poor job in advocating to explicitly delete move constructors, as that suggests he learned nothing from the ordeal. A preferable lesson would be to a) not use raw pointers and instead try to adopt a smart pointer with the relevant semantics, b) actually provide custom implementations for copy/move constructors/assignment operators whenever doing anything non-trivial to manage resources, such as handling raw pointers and needing to both copy them and free them whenever they stop being used.