Spec-Zone.ru › C++

std::deque<T,Allocator>::shrink_to_fit

void shrink_to_fit();

Запрашивает удаление неиспользуемой ёмкости.

Это необязательный к исполнению запрос на сокращение использования памяти без изменения размера последовательности. Выполнение запроса зависит от реализации.

Все итераторы (включая итератор end()) и все ссылки на элементы становятся недействительными.

Если T не является MoveInsertable в std::deque<T,Allocator>, поведение не определено.

(начиная с C++11)

Сложность

Не более линейной относительно размера контейнера.

Исключения

Если исключение выбрасывается не конструктором перемещения не-CopyInsertable T, эффект отсутствует.

(начиная с C++11)

Примечания

В libstdc++ shrink_to_fit() недоступен в режиме C++98.

Пример

#include <cstddef>
#include <deque>
#include <iostream>
#include <new>

// Minimal C++11 allocator with debug output.
template<class Tp>
struct NAlloc
{
    typedef Tp value_type;

    NAlloc() = default;

    template<class T> NAlloc(const NAlloc<T>&) {}

    Tp* allocate(std::size_t n)
    {
        n *= sizeof(Tp);
        std::cout << "allocating " << n << " bytes\n";
        return static_cast<Tp*>(::operator new(n));
    }

    void deallocate(Tp* p, std::size_t n)
    {
        std::cout << "deallocating " << n*sizeof*p << " bytes\n";
        ::operator delete(p);
    }
};
template<class T, class U>
bool operator==(const NAlloc<T>&, const NAlloc<U>&) { return true; }
template<class T, class U>
bool operator!=(const NAlloc<T>&, const NAlloc<U>&) { return false; }

int main()
{
    // std::queue has no capacity() function (like std::vector).
    // Because of this, we use a custom allocator to show the
    // working of shrink_to_fit.

    std::cout << "Default-construct deque:\n";
    std::deque<int, NAlloc<int>> deq;

    std::cout << "\nAdd 300 elements:\n";
    for (int i = 1000; i < 1300; ++i)
        deq.push_back(i);
    
    std::cout << "\nPop 100 elements:\n";
    for (int i = 0; i < 100; ++i)
        deq.pop_front();

    std::cout << "\nRun shrink_to_fit:\n";
    deq.shrink_to_fit();

    std::cout << "\nDestroy deque as it goes out of scope:\n";
}

Возможный вывод:

Default-construct deque:
allocating 64 bytes
allocating 512 bytes

Add 300 elements:
allocating 512 bytes
allocating 512 bytes

Pop 100 elements:

Run shrink_to_fit:
allocating 64 bytes
allocating 512 bytes
allocating 512 bytes
deallocating 512 bytes
deallocating 512 bytes
deallocating 512 bytes
deallocating 64 bytes

Destroy deque as it goes out of scope:
deallocating 512 bytes
deallocating 512 bytes
deallocating 64 bytes

Отчёты об ошибках

Следующие отчёты об ошибках, изменяющие поведение, были ретроактивно применены к ранее опубликованным стандартам C++.

DR Применён к Опубликованное поведение Правильное поведение
LWG 850 C++98 std::deque не предоставлял явных операций для подгонки ёмкости добавлены
LWG 2033 C++98
C++11
1. требование к сложности отсутствовало (C++98)
2. для T не требовалось соответствие требованиям MoveInsertable (C++11)
1. добавлено
2. требуется
LWG 2223 C++98
C++11
1. ссылки, указатели и итераторы не становились недействительными (C++98)
2. гарантия безопасности исключений отсутствовала (C++11)
1. они могут стать недействительными
2. добавлена

См. также

size
возвращает количество элементов
(открытая функция-член)

© cppreference.com
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.
https://en.cppreference.com/cpp/container/deque/shrink_to_fit

Spec-Zone.ru

Настройки Оффлайн Что нового Помощь О нас
Spec-Zone .ru
спецификации, руководства, описания, API