Sobes.tech
Junior — Middle

What types of smart pointers have you used in your projects?

sobes.tech AI

Answer from AI

In C++, the most commonly used smart pointers from the <memory> library are:

  • std::unique_ptr — provides exclusive ownership of an object. The object is automatically deleted when the unique_ptr goes out of scope. It cannot be copied, only moved.
  • std::shared_ptr — implements reference counting for shared ownership. The object is deleted when the last shared_ptr is destroyed.
  • std::weak_ptr — a weak reference to an object managed by shared_ptr. It does not affect the object's lifetime and is used to prevent cyclic dependencies.

Example usage:

#include <memory>
#include <iostream>

int main() {
    std::unique_ptr<int> uptr = std::make_unique<int>(10);
    std::cout << *uptr << std::endl;

    std::shared_ptr<int> sptr1 = std::make_shared<int>(20);
    std::shared_ptr<int> sptr2 = sptr1; // shared ownership

    std::weak_ptr<int> wptr = sptr1; // weak reference

    return 0;
}

Choosing a smart pointer depends on ownership and lifetime requirements in projects.