Skip to Content
Mastering C++ Programming
book

Mastering C++ Programming

by Jeganathan Swaminathan
September 2017
Beginner to intermediate
384 pages
8h 4m
English
Packt Publishing
Content preview from Mastering C++ Programming

Circular dependency

Circular dependency is an issue that occurs if object A depends on B, and object B depends on A. Now let's see how this issue could be fixed with a combination of shared_ptr and weak_ptr, eventually breaking the circular dependency, as follows:

#include <iostream>#include <string>#include <memory>#include <sstream>using namespace std;class C;class A {      private:           weak_ptr<C> ptr;      public:           A() {                  cout << "\nA constructor" << endl;           }           ~A() {                  cout << "\nA destructor" << endl;           }           void setObject ( weak_ptr<C> ptr ) {                  this->ptr = ptr;           }};class B {      private:           weak_ptr<C> ptr;      public:           B() {               cout << "\nB constructor" << endl;           }                      ~B() {               cout << "\nB destructor" << endl;           }           void setObject ( weak_ptr<C> ptr ) {                this->ptr = ptr;           }};class C { ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Multi-Paradigm Programming with Modern C++

Multi-Paradigm Programming with Modern C++

Georgy Pashkov

Publisher Resources

ISBN: 9781786461629Supplemental Content