Sobes.tech
Junior — Middle

Can you name the types of smart pointers implemented in the C++ standard library?

sobes.tech AI

Answer from AI

The C++ standard library implements three main types of smart pointers:

  • std::unique_ptr — provides exclusive ownership of an object. The object pointed to by unique_ptr is automatically destroyed when the pointer goes out of scope. It cannot be copied, only moved.

  • std::shared_ptr — implements shared ownership of an object. The object is destroyed when the last shared_ptr pointing to it is destroyed or reset.

  • std::weak_ptr — a weak reference to an object managed by shared_ptr. It does not affect the object's lifetime and allows checking whether the object still exists before accessing it.

Example usage:

#include <memory>
#include <iostream>

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

    std::shared_ptr<int> sptr1 = std::make_shared<int>(20);
    std::shared_ptr<int> sptr2 = sptr1; // sharing ownership
    std::cout << *sptr2 << std::endl; // 20

    std::weak_ptr<int> wptr = sptr1;
    if (auto spt = wptr.lock()) { // check if the object exists
        std::cout << *spt << std::endl; // 20
    }
}