C++ smart pointers and ownership
Smart pointers manage heap objects automatically, following RAII: the object is destroyed when its owner goes away. std::unique_ptr has exactly one owner, cannot be copied, and can be moved to transfer ownership. After a move the source is null. It costs nothing extra compared with a raw pointer.
C++
#include <iostream>
#include <memory>
#include <string>
struct Resource {
std::string name;
explicit Resource(std::string n) : name(std::move(n)) { std::cout << "create " << name << "\n"; }
~Resource() { std::cout << "destroy " << name << "\n"; }
};
int main() {
auto a = std::make_unique<Resource>("A");
auto b = std::move(a);
std::cout << "a is null: " << (a == nullptr) << "\n";
{
auto shared = std::make_shared<Resource>("S");
auto second = shared;
std::cout << "owners: " << shared.use_count() << "\n";
}
std::weak_ptr<Resource> weak;
{
auto temp = std::make_shared<Resource>("T");
weak = temp;
std::cout << "alive inside: " << !weak.expired() << "\n";
}
std::cout << "alive after: " << !weak.expired() << "\n";
std::cout << "end of main\n";
}