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 }

执行结果:

 

posted @ 2022-03-26 11:21  禅元天道  阅读(443)  评论(0编辑  收藏  举报