1. 程式人生 > 其它 >C++中的delete與nullptr

C++中的delete與nullptr

 1 #include <iostream>
 2 #include <list>
 3 #include <string>
 4 
 5 using namespace std;
 6 
 7 
 8 class Geometry {
 9 public:
10     string getName1()
11     {
12         return "test";
13     }
14     string getName2()
15     {
16         return name;
17     }
18 
19     friend ostream& operator
<<(ostream &out, const Geometry & geometry) { 20 return out << "Name: " << geometry.name; 21 } 22 private: 23 string name = "test"; 24 }; 25 26 27 int main(int argc, char** argv) 28 { 29 Geometry* g = new Geometry(); 30 cout << "== After new operator ==
" << endl; 31 cout << "指標指向記憶體的值:" << * g << endl; 32 cout << "指標指向記憶體的地址:" << g << endl; 33 cout << "指標本身的地址:" << &g << endl; 34 delete g; 35 cout << endl << "== After delete operator ==" << endl;
36 // cout << "指標指向記憶體的值:" << * g << endl; // 程式崩潰 37 cout << "指標指向記憶體的地址:" << g << endl; 38 cout << "指標本身的地址:" << &g << endl; 39 g = nullptr; 40 cout << endl << "== After setNullptr operator ==" << endl; 41 // cout << "指標指向記憶體的值:" << * g << endl; // 程式崩潰 42 cout << "指標指向記憶體的地址:" << g << endl; 43 cout << "指標本身的地址:" << &g << endl; 44 45 cout << endl << g->getName1() << endl; 46 // cout << g->getName2() << endl; // 程式崩潰 47 return 0; 48 }

執行結果: