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 theunique_ptrgoes out of scope. It cannot be copied, only moved.std::shared_ptr— implements reference counting for shared ownership. The object is deleted when the lastshared_ptris destroyed.std::weak_ptr— a weak reference to an object managed byshared_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.