In C++, smart pointers are an important part of memory management that help in automatically handling resource management. The three main types of smart pointers are unique_ptr, shared_ptr, and weak_ptr.
A unique_ptr
is a smart pointer that owns a dynamically allocated object and ensures that there is only one unique pointer to that object. When the unique_ptr
goes out of scope, the associated object is destroyed. This prevents memory leaks and deallocation issues.
A shared_ptr
allows multiple pointers to share ownership of the same dynamically allocated object. The object is destroyed when the last shared_ptr
pointing to it is destroyed or reset. This is useful in scenarios where ownership needs to be shared across different parts of the program.
A weak_ptr
provides a way to refer to a shared_ptr
object without affecting its reference count. This can help prevent circular references and memory leaks in scenarios where two objects reference each other.
#include <iostream>
#include <memory>
class MyClass {
public:
MyClass() { std::cout << "MyClass constructed." << std::endl; }
~MyClass() { std::cout << "MyClass destructed." << std::endl; }
};
int main() {
// Using unique_ptr
std::unique_ptr uniquePtr = std::make_unique();
// Using shared_ptr
std::shared_ptr sharedPtr1 = std::make_shared();
std::shared_ptr sharedPtr2 = sharedPtr1; // shared ownership
// Using weak_ptr
std::weak_ptr weakPtr = sharedPtr1; // does not affect reference count
return 0;
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?