C++ Memory Management Library<memory>

<memory>It is a header file in the C++ standard library that contains templates and functions for dynamic memory management.

In C++, memory management is an important concept. Dynamic memory management allows programs to allocate and release memory at runtime, which is very useful when handling data structures of uncertain size. However, incorrect memory management can lead to problems such as memory leaks and dangling pointers.

<memory>The header file provides tools such as smart pointers to help developers manage dynamic memory more safely.

Smart Pointers

Smart pointers are<memory>The core content in the header file. They are features introduced in C++11, used to automatically manage dynamically allocated memory. The main types of smart pointers are:

  • std::unique_ptr: An exclusive-ownership smart pointer; at any one time, only oneunique_ptrPoints to specific memory.
  • std::shared_ptr: a smart pointer with shared ownership, multipleshared_ptrcan point to the same memory, and the memory is in the last one.shared_ptrReleased when destroyed.
  • std::weak_ptr: a weak reference smart pointer, used withshared_ptrused together, to avoid memory leaks caused by circular references.

Example

Usagestd::unique_ptr

Example

#include <iostream>
#include <memory>

class MyClass {
public:
    void doSomething() {
        std::cout << "Doing something" << std::endl;
    }
};

int main() {
    std::unique_ptr<MyClass> myPtr(new MyClass());
    myPtr->doSomething(); // Use smart pointer to call member function

    // When the main function ends, myPtr is destroyed, automatically freeing the memory of the MyClass object.
    return 0;
}

Output result:

Doing something

Usagestd::shared_ptr

Example

#include <iostream>
#include <memory>

class MyClass {
public:
    void doSomething() {
        std::cout << "Doing something" << std::endl;
    }
};

int main() {
    std::shared_ptr<MyClass> myPtr1(new MyClass());
    std::shared_ptr<MyClass> myPtr2 = myPtr1;

    myPtr1->doSomething(); // Use myPtr1 to call member function
    myPtr2->doSomething(); // Use myPtr2 to call member function

    // Only when both myPtr1 and myPtr2 are destroyed will the memory of the MyClass object be released.
    return 0;
}

Output result:

Doing something
Doing something

Usagestd::weak_ptr

std::weak_ptrUsually not used alone, but rather withstd::shared_ptrused in combination, to solve the circular reference issue.

Example

#include <iostream>
#include <memory>

class Node {
public:
    std::shared_ptr<Node> next;
    std::weak_ptr<Node> prev;

    Node() : next(nullptr), prev() {}
};

int main() {
    std::shared_ptr<Node> node1 = std::make_shared<Node>();
    std::shared_ptr<Node> node2 = std::make_shared<Node>();

    node1->next = node2;
    node2->prev = node1;

    // Circular reference, but using weak_ptr avoids memory leak.
    return 0;
}

In this example,node1andnode2creates a circular reference. SinceprevYesweak_ptr, whennode1andnode2ofshared_ptrWhen destroyed, the memory they point to is also correctly released.

Allocator

Allocators are another important part of <memory>.

Allocators are used to allocate memory for containers; all containers in the standard library use allocators to handle memory allocation.

std::allocator

std::allocator is the standard allocator, providing basic memory allocation and deallocation functions.

Example

#include <memory>
#include <vector>

int main() {
    std::allocator<int> alloc;
    int* p = alloc.allocate(1); // Allocate memory
    alloc.construct(p, 42); // Construct object

    std::cout << *p << std::endl;

    alloc.destroy(p); // Destroy object
    alloc.deallocate(p, 1); // release memory

    return 0;
}

Other memory management tools

std::align

std::align is used to adjust the alignment of pointers to ensure that the allocated memory meets specific alignment requirements.

Example

#include <memory>
#include <iostream>

int main() {
    alignas(16) char buffer[64];
    void* p = buffer;
    size_t space = sizeof(buffer);

    void* aligned_ptr = std::align(16, sizeof(int), p, space);
    if (aligned_ptr) {
        std::cout << "Memory aligned\n";
    } else {
        std::cout << "Memory alignment failed\n";
    }

    return 0;
}

<memory>The header file is an important part of the C++ standard library for handling dynamic memory management.

By using smart pointers, such asunique_ptr、shared_ptrandweak_ptr, developers can manage memory more safely and effectively, avoiding common memory management errors. I hope this article can help beginners better understand and use C++'s<memory>Header file.

other extensions