Live data from Hacker News

Retiring a favourite C++ joke

ignition-training.com

41–50 of 151 posts

Re: Retiring a favourite C++ joke

#44

#include using namespace std; class BadProgrammer { public: void yep() { delete this; } }; int main() { auto x = BadProgrammer{}; x.yep(); cout g++ -Wall -Wextra -Wpedantic main.cc # compiles just fine clang++ -Wall -Wextra -Wpedantic main.cc # also compiles just fine

[deleted]

Re: Retiring a favourite C++ joke

#46
post #38

I was surprised to see it not mentioned in the post -- the most obvious reason this joke should be retired is not the reference to a television show but rather the modern practice of never using new or delete at all in C++ code. Modern C++ avoids these pitfalls and I think it's been 10 years since I've written the words the new or delete.

That modern pratice is more theory than practice, even on sample code from ISO C++ members.

Re: Retiring a favourite C++ joke

#48

#include using namespace std; class BadProgrammer { public: void yep() { delete this; } }; int main() { auto x = BadProgrammer{}; x.yep(); cout g++ -Wall -Wextra -Wpedantic main.cc # compiles just fine clang++ -Wall -Wextra -Wpedantic main.cc # also compiles just fine

FWIW the behavior of delete on a pointer that isn’t either null or returned from new is undefined.

So a conforming C++ compiler doesn’t have to diagnose this mistake, and similarly the compiled program doesn’t have to do anything meaningful either. For example, just ignoring the delete and printing the message is as valid a result as the more useful crash at the site of the bad operation.

Re: Retiring a favourite C++ joke

#50
> void fn() { int tobias; delete &tobias; } : ** error pointer being freed was not allocated

i wouldn't say that's an illegal op per se, if anything it's a pretty safe op! tobias only ever existed in thought, not in body :( :(

maybe a compiler WARN or IGNORED_OP

Post reply on HN