Junior — Middle
What are the main challenges or pitfalls associated with using smart pointers in programming?
sobes.tech AI
Answer from AI
Main challenges when using smart pointers:
- Cyclic references: if two objects own each other through
shared_ptr, they will never be released, causing a memory leak. To solve this,weak_ptris used. - Incorrect use of
unique_ptr: attempting to copy aunique_ptrwill result in an error; move semantics should be used instead. - Resource overload: frequent creation and destruction of smart pointers can affect performance.
- Non-obvious ownership: improper design makes it difficult to understand who owns the object and when it will be destroyed.
Example of a cyclic reference:
struct B;
struct A {
std::shared_ptr<B> b_ptr;
};
struct B {
std::shared_ptr<A> a_ptr;
};
// This creates a cycle, and objects will not be automatically deleted.
To avoid this, std::weak_ptr is used for one of the sides.