Memory and RAII
Memory and RAII
Object lifetime, stack vs heap, smart pointers, and resource safety patterns.
Memory and RAII
Object lifetime, stack vs heap, smart pointers, and resource safety patterns.
static localsnew or factory helpersResource Acquisition Is Initialization means the object owns the resource and releases it in the destructor.
class FileHandle {
public:
explicit FileHandle(std::FILE* file) : file_{file} {}
~FileHandle() {
if (file_) std::fclose(file_);
}
private:
std::FILE* file_{};
};
auto p = std::make_unique<int>(42);
auto s = std::make_shared<std::string>("hello");
std::weak_ptr<std::string> weak = s;
std::unique_ptr: single ownerstd::shared_ptr: shared ownershipstd::weak_ptr: non-owning observer for shared graphsstd::vector<std::string> names;
std::string temp = "Ada";
names.push_back(std::move(temp));
Move when ownership or expensive state should transfer, not just because std::move exists.
new and delete in application code.std::unique_ptr by default.std::move only when you are done with the source object.using FilePtr = std::unique_ptr<std::FILE, int(*)(std::FILE*)>;
FilePtr file(std::fopen("data.txt", "r"), &std::fclose);
Custom deleters let smart pointers manage non-memory resources such as file handles, sockets, or OS descriptors.
struct Node {
std::shared_ptr<Node> next;
std::weak_ptr<Node> prev;
};
If both directions used std::shared_ptr, the nodes could keep each other alive forever. Use std::weak_ptr to break cycles.
std::span, std::string_view, raw pointers, and references do not extend lifetime.open() / close() pairs.noexcept when possible to keep containers efficient.std::unique_ptrstd::shared_ptrstd::span, or std::string_view#include <memory>
int main() {
auto resource = std::make_unique<int>(7);
return *resource;
}
Transfer ownership out of one scope and into another with `std::move`. It is the fastest way to see what unique ownership really means.
#include <memory>
std::unique_ptr<int> make_value() {
auto value = std::make_unique<int>(42);
return value;
}