memory


Header: <memory>

The <memory> header is a crucial part of the C++ Standard Library, providing a collection of tools for memory management and smart pointers. It offers various components that help developers manage dynamic memory allocation, object lifetime, and resource ownership more effectively and safely.

Key Characteristics

Key Components

Smart Pointers

  1. unique_ptr: For exclusive ownership of dynamically allocated objects
  2. shared_ptr: For shared ownership of dynamically allocated objects
  3. weak_ptr: A non-owning observer for shared_ptr

Allocators

  1. allocator: The default allocator for the C++ Standard Library
  2. allocator_traits: Provides a uniform interface to allocator types

Memory Management Functions

  1. make_unique: Creates a unique_ptr (C++14 and later)
  2. make_shared: Creates a shared_ptr
  3. uninitialized_copy, uninitialized_fill: For raw memory operations

Example 1: Using unique_ptr

#include <iostream>
#include <memory>

class MyClass {
public:
    MyClass() { std::cout << "MyClass constructed\n"; }
    ~MyClass() { std::cout << "MyClass destructed\n"; }
    void doSomething() { std::cout << "Doing something\n"; }
};

int main() {
    std::unique_ptr<MyClass> ptr = std::make_unique<MyClass>();
    ptr->doSomething();

    // No need to delete, unique_ptr handles it automatically
    return 0;
}

Explanation

Example 2: Shared Ownership with shared_ptr

#include <iostream>
#include <memory>

class Resource {
public:
    Resource() { std::cout << "Resource acquired\n"; }
    ~Resource() { std::cout << "Resource released\n"; }
    void use() { std::cout << "Resource used\n"; }
};

void useResource(std::shared_ptr<Resource> res) {
    std::cout << "Resource use count: " << res.use_count() << std::endl;
    res->use();
}

int main() {
    auto res = std::make_shared<Resource>();
    useResource(res);

    {
        auto res2 = res;
        useResource(res);
    }

    useResource(res);
    return 0;
}

Explanation

Example 3: Custom Allocator

#include <iostream>
#include <memory>
#include <vector>

template <typename T>
class TrackingAllocator : public std::allocator<T> {
public:
    using size_type = size_t;
    using pointer = T*;
    using const_pointer = const T*;

    template <typename U>
    struct rebind {
        typedef TrackingAllocator<U> other;
    };

    pointer allocate(size_type n, const void* hint = 0) {
        std::cout << "Allocating " << n << " objects\n";
        return std::allocator<T>::allocate(n, hint);
    }

    void deallocate(pointer p, size_type n) {
        std::cout << "Deallocating " << n << " objects\n";
        std::allocator<T>::deallocate(p, n);
    }
};

int main() {
    std::vector<int, TrackingAllocator<int>> v;
    for (int i = 0; i < 10; ++i) {
        v.push_back(i);
    }
    return 0;
}

Explanation

Additional Considerations

Summary

The <memory> header in C++ provides a comprehensive set of tools for effective memory management. Its smart pointer classes (unique_ptr, shared_ptr, and weak_ptr) offer automatic and safe management of dynamically allocated resources, helping to prevent memory leaks and other common pitfalls associated with manual memory management.

The header also includes allocator classes and functions that allow for customization of memory allocation strategies, which can be particularly useful in performance-critical applications or when working with non-standard memory models.

By leveraging the components provided by <memory>, C++ developers can write more robust, efficient, and exception-safe code, particularly when dealing with dynamic memory allocation and resource management. The smart pointers and allocators work seamlessly with other parts of the C++ Standard Library, making it easier to write correct and efficient code in modern C++ applications.

Citations:

[1] https://www.simplilearn.com/tutorials/cpp-tutorial/cpp-memory-management [2] https://en.cppreference.com/w/cpp/header/memory [3] https://www.geeksforgeeks.org/cpp-17-memory_resource-header/ [4] https://www.geeksforgeeks.org/smart-pointers-cpp/ [5] https://www.geeksforgeeks.org/auto_ptr-unique_ptr-shared_ptr-weak_ptr-in-cpp/ [6] https://www.reddit.com/r/cpp_questions/comments/17tl7oh/best_practice_smart_pointer_use/ [7] https://www.modernescpp.com/index.php/c-core-guidelines-rules-to-smart-pointers/

Previous Page | Course Schedule | Course Content