Skip to content

Instantly share code, notes, and snippets.

@thuvh
Created October 24, 2018 17:12
Show Gist options
  • Save thuvh/4fe7eceb2c3f53cf1fc7703f70a1947d to your computer and use it in GitHub Desktop.
Save thuvh/4fe7eceb2c3f53cf1fc7703f70a1947d to your computer and use it in GitHub Desktop.
cpp pointer
#include <iostream>
using namespace std;
int main(){
int a = 3;
int *p, *q;
p = &a;
q = p;
cout << p << ", " << q << endl;
cout << *p << ", " << *q << endl;
delete p;
//cout << p << ", " << q << endl;
//if (p == NULL){
// cout << "p is null" << endl;
//}
if (q == NULL){
cout << "q is null" << endl;
}
//cout << *q << endl;
return 0;
}
// operator delete example
#include <iostream> // std::cout
using namespace std;
struct MyClass {
MyClass() {std::cout <<"MyClass constructed\n";}
~MyClass() {std::cout <<"MyClass destroyed\n";}
void t(){
cout << "hello" << endl;
}
};
int main () {
MyClass * pt = new (std::nothrow) MyClass;
cout << "1" << endl;
MyClass * q = new (std::nothrow) MyClass;
cout << "2" << endl;
q = pt;
cout << "3" << endl;
delete pt; // implicitly calls ::operator delete(pt)
cout << "4" << endl;
q->t();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment