In C++11, smart pointers like std::unique_ptr
and std::shared_ptr
are used to manage the lifetime of dynamically allocated objects, ensuring proper memory management and reducing the possibility of memory leaks.
std::unique_ptr
is used when you want to have sole ownership of an object, ensuring that no two unique pointers point to the same object.
#include <iostream>
#include <memory>
class MyClass {
public:
MyClass() { std::cout << "MyClass created" << std::endl; }
~MyClass() { std::cout << "MyClass destroyed" << std::endl; }
};
int main() {
std::unique_ptr ptr1(new MyClass());
// std::unique_ptr ptr2 = ptr1; // This will cause a compile error
std::unique_ptr ptr2 = std::move(ptr1); // Transfer ownership
return 0;
}
std::shared_ptr
is used when you want to allow multiple owners for the same object. It keeps track of how many shared pointers point to the same object.
#include <iostream>
#include <memory>
class MyClass {
public:
MyClass() { std::cout << "MyClass created" << std::endl; }
~MyClass() { std::cout << "MyClass destroyed" << std::endl; }
};
int main() {
std::shared_ptr ptr1(new MyClass());
{
std::shared_ptr ptr2 = ptr1; // Shared ownership
std::cout << "Use count: " << ptr1.use_count() << std::endl; // 2
}
std::cout << "Use count after ptr2 goes out of scope: " << ptr1.use_count() << std::endl; // 1
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?