C++ Deque::get_allocator() Function



The C++ std::deque::get_allocator() function is used to return the copy of the allocator object associated with the deque. This allocator object is responsible for managing the memory allocations and deallocation for the elements within the deque. By accessing the allocator, we can control or customize the memory management.

Syntax

Following is the syntax for std::deque::get_allocator() function.

allocator_type get_allocator() const noexcept;

Parameters

It does not accept any parameter.

Return value

It returns an allocator associated with deque.

Exceptions

This function never throws exception.

Time complexity

The time complexity of this function is Constant i.e O(1)

Example

In the following example, we are going to consider the basic usage of the get_allocator() function.

#include <iostream>
#include <deque>
#include <memory>
int main()
{
    std::deque<char> a;
    std::allocator<char> x = a.get_allocator();
    char* y = x.allocate(1);
    x.construct(y, 'A');
    std::cout << "Value constructed in allocated memory: " << *y << std::endl;
    x.destroy(y);
    x.deallocate(y, 1);
    return 0;
}

Output

Output of the above code is as follows −

Value constructed in allocated memory: A

Example

Consider the following example, where we are going to create a another deque using the same allocator as the first deque.

#include <iostream>
#include <deque>
int main()
{
    std::deque<int> a = {1, 22,333,4444};
    std::deque<int> b(a.get_allocator());
    b.push_back(123);
    b.push_back(345);
    for (int val : b) {
        std::cout << val << " ";
    }
    std::cout << std::endl;
    return 0;
}

Output

Following is the output of the above code −

123 345 
deque.htm