Reduce the size of the container of non-standard default elements using unified resizing

Using push_back/ emplace_back(rare push_front/ emplace_frontor even push_after/ emplace_after), I can fill almost any container from STL. Even a container of custom items. Reducing the size only requires the presence of element destructors (moreover, containers necessarily require that the elements be Destructible ). But I can’t just use resize(if present) to reduce the size of the containers of non-standard default elements. Instead, I have to use a workaround, even for the least demanding (to their special features) std::list.

#include <list>

#include <cstdlib>

int
main()
{
    // construct
    std::list< std::reference_wrapper< int > > l;
    // fill
    int i{};
    l.emplace_back(i);
    int j{};
    l.emplace_back(j);
    // save intermediate state for future
    std::size_t const size = l.size();
    // continue appending
    int k{};
    l.emplace_back(k);
    // now I want to rollback to saved state
    //l.resize(size); // just need to call the destructors, but illegal due to not default constructible value_type
    // so I have to use a workaround
    for (std::size_t s = l.size(); size < s; --s) {
        l.pop_back();
    }
    return EXIT_SUCCESS;
}

std::list::resize std::list::value_type DefaultInsertable.

, resize(std::size_t) " " . resize(std::size_t, value_type = value_type()) (, ) resize(std::size_t)/resize(std::size_t, value_type), value_type DefaultConstructible. , , resize(std::size_t) , , std::bad_alloc. ?

+4
1

value_type (DefaultInsertable), resize . , .

resize, , . value_type .

, l.resize(size, dummy_value), . dummy_value l.front() , . size l.size(), .

+3

Source: https://habr.com/ru/post/1624488/


All Articles