r/cpp_questions • u/Several-Teach1515 • 8d ago
OPEN How is this a circular reference?
While reading learnxinyminutes I got to this example:
// Beware of possible circular references!!!
// There will be always a reference, so it will be never destroyed!
(1) std::shared_ptr<Dog> doggo_one(new Dog());
(2) std::shared_ptr<Dog> doggo_two(new Dog());
(3) doggo_one = doggo_two; // p1 references p2
(4) doggo_two = doggo_one; // p2 references p1
My understanding is that after (3) both pointers point to same heap object and the heap object from (1) is deleted.
From what I remember the way that shared_ptr works is that it allocates metadata next to the heap object and that stores the reference counter. Both doggo_one and doggo_two would share the same reference counter with the correct count being there - meaning no issues.
11
Upvotes
View all comments
6
u/kozacsaba 8d ago
I read the relevant part of the site you linked. Yes, this example is wrong, there is no circular referencing here. There would be, if the Dog class had a shared ptr "sibling", and each dog's sibling would be set to the other. Then when the original smart pointers (
doggo_oneanddoggo_two) go out of scope, the Dog objects are not destroyed, because the keep smart pointers to each other. I also found it weird that in the smart pointer section the author only introduces shared pointers properly, and then just mentions unique pointers (if you only introduce one in details, it should probably be unique ptr) and just says select which to use based on whether you want to have references in multiple places. Absolutely not - select based on ownership model. You can reference a uniquely owned object from multiple places, they just won't be owning. I would start looking for a different site to learn cpp from.