1 #include <iostream> 2 #include <memory> 3 4 using namespace std; 5 6 class T 7 { 8 public: 9 T() 10 { 11 std::cout << "T()" << std::endl; 12 } 13 14 ~T() 15 { 16 std::cout << "~T()" << std::endl; 17 } 18 }; 19 20 int main() 21 { 22 { 23 T *t1 = new T(); 24 } 25 26 { 27 T *t2 = new T(); 28 std::shared_ptr<T> t3(t2); 29 } 30 31 return 0; 32 }
運行結果:
第28行就是將普通指針轉換成了智能指針,出了作用域之后也成功析構了。
一個普通指針智能轉化一次智能指針,之后的操作要在智能指針上進行。
代碼:
1 #include <iostream> 2 #include <memory> 3 4 using namespace std; 5 6 class T 7 { 8 public: 9 T() 10 { 11 std::cout << "T()" << std::endl; 12 } 13 14 ~T() 15 { 16 std::cout << "~T()" << std::endl; 17 } 18 19 private: 20 int t[1024]; 21 }; 22 23 int main() 24 { 25 { 26 T *t1 = new T(); 27 } 28 29 { 30 T *t2 = new T(); 31 std::shared_ptr<T> t3(t2); 32 33 std::shared_ptr<T> t4(t2); 34 35 } 36 37 return 0; 38 }
類里面定義了一個數組,用於析構釋放堆空間時復現問題,否則不容易復現。
運行結果:
31、33行會導致析構兩次,產生了內存錯誤。