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));
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.
std::span, std::string_view, raw pointers, and references do not extend lifetime.open() / close() pairs.noexcept when possible to keep containers efficient.