Wednesday, January 08, 2020

C++ smart pointers vs Rust

Smart pointers (Modern C++) | Microsoft Docs

"As shown in the example, a smart pointer is a class template that you declare on the stack, and initialize by using a raw pointer that points to a heap-allocated object. After the smart pointer is initialized, it owns the raw pointer. This means that the smart pointer is responsible for deleting the memory that the raw pointer specifies. The smart pointer destructor contains the call to delete, and because the smart pointer is declared on the stack, its destructor is invoked when the smart pointer goes out of scope, even if an exception is thrown somewhere further up the stack."

void UseRawPointer() { // 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() { // Declare a smart pointer on stack and pass it the raw pointer. unique_ptr song2(new Song(L"Nothing on You", L"Bruno Mars")); // Use song2... wstring s = song2->duration_; //... } // song2 is deleted automatically here.

Smart Pointers in C++ - GeeksforGeeks

intro/smart pointers - cppreference.com


How to think about Rust ownership versus C++ unique_ptr · Franklin Chen

Learning smart pointers in C++ and Rust | Junchao's blog

Smart Pointers - The Rust Programming Language