The Automatic Management Method of C++ Pointer

method one:

Use smart pointers unique_ptr<>, shared_ptr<> for automatic management.

Method Two:

Use local variables to dereference it in the local environment, and automatically destruct it when the function ends.

 1 #include <iostream>
 2 #include <string>
 3 
 4 class A
 5 {
 6 private:
 7         std::string s;
 8 public:
 9         A(std::string s) { this->s = s; }
10         ~A() { std::cout << this->s << "~A()" << std::endl; }
11 };
12 
13 int main()
14 {
15         A *a = new A("A");
16         A b("B");
17         A *c = new A("C");
18         A tc = *c;
19         return 0;
20 }

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325387374&siteId=291194637