The RAII mechanism is described in C++ memory management, which automatically initializes stack variables when they are declared, and automatically fires destructors when stack variables are out of scope.
A concrete implementation of this RAII idea is the smart pointer, which is an internal class that can encapsulate any type through template class technology. Resource objects can be stored in heap memory in such a way that parameters can be passed in generic Pointers, and pointer operations can be simulated through operator overloading.
Here is a comparison of the primitive pointer to the smart pointer
void UseRawPointer(a)
{
// Using a raw pointer -- not recommended.
Song* pSong = new Song(L"Nothing on You".L"Bruno Mars");
// Use pSong...
// Don't forget to delete!
delete pSong;
}
void UseSmartPointer(a)
{
// Declare a smart pointer on stack and pass it the raw pointer.
unique_ptr<Song> song2(new Song(L"Nothing on You".L"Bruno Mars"));
// Use song2...
wstring s = song2->duration_;
/ /...
} // song2 is deleted automatically here.
Copy the code
Refer to the reference
Docs.microsoft.com/zh-cn/cpp/c…