Practice mode C++

Two objects hold std::shared_ptr references to each other. What problem does this cause and what is the usual fix?

Correct answer B. A reference cycle prevents either object being freed; make one link a std::weak_ptr

Explanation

shared_ptr frees an object only when its owner count reaches zero. In a cycle, each object keeps the other's count at least one, so neither is ever destroyed and the memory leaks. std::weak_ptr observes an object without owning it, so making one direction (often the back-pointer to a parent) weak breaks the cycle. shared_ptr has no cycle detection.

Report a problem

Answer checked How we write and check questions

Tip: press A, B, C or D to answer, and N for the next question.

Advertisement

Have a question about this answer?

Your email address will not be published. Required fields are marked *

Links and website addresses are not allowed in comments.