skip to content
Ivan's wiki
Site Tools
Search
Tools
Show pagesource
Backlinks
Recent Changes
Media Manager
Sitemap
>
Recent Changes
Media Manager
Sitemap
hpp-memory
This page is read only. You can view the source, but not change it.
# <memory> **[<memory>](https://en.cppreference.com/w/cpp/header/memory)** provides smart pointers—`std::unique_ptr<T>` (exclusive ownership), `std::shared_ptr<T>` (reference-counted ownership)—and `std::make_unique`, `std::make_shared` factories. Smart pointers automatically delete memory via RAII, preventing leaks and use-after-free. Use `std::unique_ptr` by default; use `std::shared_ptr` only when you need shared ownership semantics. Avoid raw `new`/`delete` in modern C++. This example demonstrates exclusive ownership with unique_ptr and reference-counted ownership with shared_ptr, showing automatic cleanup. ```cpp // compile: g++ -std=c++11 -o memoryexample memoryexample.cpp // run: ./memoryexample // description: smart pointers and automatic cleanup #include <memory> #include <iostream> int main() { { auto ptr = std::make_unique<int>(42); std::cout << "unique_ptr value: " << *ptr << "\n"; } auto sptr = std::make_shared<int>(99); { auto sptr2 = sptr; std::cout << "use_count: " << sptr.use_count() << "\n"; } std::cout << "use_count after scope: " << sptr.use_count() << "\n"; return 0; } ```
Page Tools
Show pagesource
Backlinks
Back to top