In C++, when using smart pointers like shared_ptr
and weak_ptr
, it's essential to avoid cycles that can lead to memory leaks. A cycle occurs when two or more objects reference each other through shared_ptr
, preventing their memory from being released. To circumvent this problem, you can use weak_ptr
for one of the references in the cycle. This way, the weak pointer does not contribute to the reference count, allowing the involved objects to be deleted when they are no longer needed.
Here’s an example that demonstrates how to avoid cycles using shared_ptr
and weak_ptr
in C++:
#include <iostream>
#include <memory>
class B; // Forward declaration
class A {
public:
std::shared_ptr bPtr;
~A() { std::cout << "A destroyed" << std::endl; }
};
class B {
public:
std::weak_ptr aPtr; // weak_ptr to avoid cycle
~B() { std::cout << "B destroyed" << std::endl; }
};
int main() {
std::shared_ptr a = std::make_shared();
std::shared_ptr b = std::make_shared();
a->bPtr = b;
b->aPtr = a; // Now B holds a weak_ptr to A
return 0; // Both A and B will be destroyed properly
}
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?