Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lære Circular References and Shared Pointers | Shared Pointers
C++ Smart Pointers

bookCircular References and Shared Pointers

When working with std::shared_ptr, you might encounter an issue known as a circular reference. A circular reference occurs when two objects hold shared_ptr references to each other. Since shared_ptr uses reference counting, the count never reaches zero, causing a memory leak.

main.cpp

main.cpp

copy
1234567891011121314151617181920212223242526
#include <iostream> #include <memory> class B; // Forward declaration class A { public: std::shared_ptr<B> p_b; ~A() { std::cout << "A destroyed\n"; } }; class B { public: ~B() { std::cout << "B destroyed\n"; } std::shared_ptr<A> p_a; }; int main() { std::shared_ptr<A> a = std::make_shared<A>(); std::shared_ptr<B> b = std::make_shared<B>(); a->p_b = b; b->p_a = a; }

There is a way to fix this issue you need to use a different type of smart pointer.

question mark

What problem does a circular reference cause in std::shared_ptr?

Select the correct answer

Var alt klart?

Hvordan kan vi forbedre det?

Tak for dine kommentarer!

Sektion 3. Kapitel 3

Spørg AI

expand

Spørg AI

ChatGPT

Spørg om hvad som helst eller prøv et af de foreslåede spørgsmål for at starte vores chat

bookCircular References and Shared Pointers

When working with std::shared_ptr, you might encounter an issue known as a circular reference. A circular reference occurs when two objects hold shared_ptr references to each other. Since shared_ptr uses reference counting, the count never reaches zero, causing a memory leak.

main.cpp

main.cpp

copy
1234567891011121314151617181920212223242526
#include <iostream> #include <memory> class B; // Forward declaration class A { public: std::shared_ptr<B> p_b; ~A() { std::cout << "A destroyed\n"; } }; class B { public: ~B() { std::cout << "B destroyed\n"; } std::shared_ptr<A> p_a; }; int main() { std::shared_ptr<A> a = std::make_shared<A>(); std::shared_ptr<B> b = std::make_shared<B>(); a->p_b = b; b->p_a = a; }

There is a way to fix this issue you need to use a different type of smart pointer.

question mark

What problem does a circular reference cause in std::shared_ptr?

Select the correct answer

Var alt klart?

Hvordan kan vi forbedre det?

Tak for dine kommentarer!

Sektion 3. Kapitel 3
some-alt