4 ms·
#include <iostream> using namespace std; class BadProgrammer { public: void yep() { delete this; } }; int main() {
by sacnoradhq 4y ago
#include <iostream>
using namespace std;
class BadProgrammer {
public:
void yep() {
delete this;
}
};
int main() {
auto x = BadProgrammer{};
x.yep();
cout << "You are a terrible engineer and should feel bad, but don't worry because this will never print." << endl;
return 0;
}
g++ -Wall -Wextra -Wpedantic main.cc # compiles just fine
clang++ -Wall -Wextra -Wpedantic main.cc # also compiles just fine
- deleted 4y ago[deleted]
- deleted 4y ago[deleted]
- akhosravian 4y agoFWIW 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.
- AnIdiotOnTheNet 4y agoThat this situation is "working as intended" and there are programmers who do not see a problem with that is... well it makes me despair.
- PaulDavisThe1st 4y agoWhat's your proposed alternative? What does the alternative cost? If non-zero, what mechanism would you use to disable it?