Sobes.tech
Middle

In which cases when using smart pointers will the delete operator not be called for the object?

sobes.tech AI

Answer from AI

  • In case of cyclic dependencies between objects managed by std::shared_ptr.
  • When using std::unique_ptr with a custom deleter that does not call delete.
  • When using std::shared_ptr with a custom deleter that does not call delete.
  • When passing std::shared_ptr or std::unique_ptr to a function or structure that stores a "raw" pointer to the object but does not manage its lifetime.
  • When using std::weak_ptr, which does not increase the reference count and does not own the object.
  • If an exception is thrown during the creation of an object or std::shared_ptr before the completion of the std::shared_ptr constructor. In this case, std::shared_ptr may not be fully constructed, and memory management could be incorrect.
  • When using std::unique_ptr with transfer of ownership (e.g., via std::move) to another std::unique_ptr, and the original unique_ptr goes out of scope. delete will be called for the new owner.
  • If the smart pointer has not gone out of scope and has not been explicitly reset (reset()).
  • When using std::unique_ptr or std::shared_ptr to manage memory allocated with non-standard allocators or functions (e.g., malloc), if a custom deleter is not provided. The standard delete will be called, which can lead to undefined behavior.