News for hackers. Stuff that matters.
Re:Code Health: Make Interfaces Hard to Misuse (2018) by GeneralMayhem on Sunday September 06, 2020 @01:21PM (#24392921)
>we can't prevent code being called too late

You can get pretty close in C++. All it takes is for the disconnect method to be rvalue-qualified:

void disconnect() &&;

and to turn on use-after-move compiler warnings. Now disconnecting has to be invoked as:

std::move(db).disconnect();

and if you refer to db after that Clang will tell you to knock it off. (Of course, for a database object, it probably makes more sense to use RAII and disconnect in the destructor, but this pattern can help if you have multiple ways for the object's useful lifetime to end.)

That won't catch users who have a pointer or reference alias to the object, but that's more like a use-after-free risk, which exists any time you have references.

There are no comments on this comment yet.