How it works...

Although they should be avoided, circular references are likely to occur as your projects grow more and more complex and in size. If shared smart pointers are leveraged when these circular references occur, a hard to find memory leak can occur. To understand how this is possible, let's look at the following example:

class car;class engine;

As shown in the preceding code, we start with two class prototypes. Circular references almost always start in this fashion as one class depends on another and vice versa, requiring the use of a class prototype.

Let's define a car as follows:

class car{    friend void build_car();    std::shared_ptr<engine> m_engine;public:    car() = default;};

As shown in the preceding code, this is a simple class ...

Get Advanced C++ Programming Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.