Skip to content

Instantly share code, notes, and snippets.

@raggleton
Created January 21, 2021 08:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save raggleton/e063131090f4e7adb95a6eda55b03a46 to your computer and use it in GitHub Desktop.
Save raggleton/e063131090f4e7adb95a6eda55b03a46 to your computer and use it in GitHub Desktop.
Testing raw pointer deletion. Compile with `g++ -o demo -g -O0 -Wall pointer_demo.cc `
#include <iostream>
#include <vector>
using namespace std;
class A {
public:
A(): thing(nullptr) {}
void DoThing(int * x) {
if (x != thing) {
delete thing;
thing = x;
}
}
int * thing;
};
int main() {
cout << "running demo" << endl;
A a;
cout << "a.thing: " << a.thing << endl;
int * xxx = new int(3);
a.DoThing(xxx);
cout << "a.thing: " << a.thing << " : " << *(a.thing) << endl;
cout << "xxx: " << xxx << " : " << *xxx << endl;
int * yyy = new int(4);
a.DoThing(yyy);
cout << "a.thing: " << a.thing << " : " << *(a.thing) << endl;
cout << "xxx: " << xxx << " : " << *xxx << endl;
cout << "yyy: " << yyy << " : " << *yyy << endl;
cout << "Trying to delete xxx:" << endl;
if (xxx != NULL) {
cout << "xxx is not NULL" << endl;
delete xxx;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment