原始指针:通过new建立的*指针

智能指针:通过智能指针关键字(unique_ptr, shared_ptr ,weak_ptr)建立的指针

 

在现代 C++ 编程中,标准库包含智能指针,该指针用于确保程序不存在内存和资源泄漏且是异常安全的。在现代 C++ 中,原始指针仅用于范围有限的小代码块、循环或者性能至关重要且不会混淆所有权的 Helper 函数中。

 1 void UseRawPointer()
 2 {
 3     // Using a raw pointer -- not recommended.
 4     Song* pSong = new Song(L"Nothing on You", L"Bruno Mars"); 
 5 
 6     // Use pSong...
 7 
 8     // Don't forget to delete!
 9     delete pSong;   
10 }
11 
12 
13 void UseSmartPointer()
14 {
15     // Declare a smart pointer on stack and pass it the raw pointer.
16     unique_ptr<Song> song2(new Song(L"Nothing on You", L"Bruno Mars"));
17 
18     // Use song2...
19     wstring s = song2->duration_;
20     //...
21 
22 } // song2 is deleted automatically here.
智能指针和原始指针比较

相关文章:

  • 2021-05-15
  • 2021-11-19
  • 2021-09-03
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2021-07-30
  • 2022-12-23
  • 2021-06-13
  • 2022-12-23
  • 2021-06-13
相关资源
相似解决方案