In a prior thread about an update to Visual Studio 2015 std::list::sort
handling a list with no default allocators, this was one of the examples used to create such a list, based on a Microsoft example for no default allocator.
I'm trying to figure out how to create an instance of a std::list
with an initial (non-zero) size, without having to do a resize after creating an empty list.
// this part of the code based on Microsoft example
template <class T>
struct Mallocator
{
typedef T value_type;
Mallocator(T) noexcept {} //default ctor not required by STL
// A converting copy constructor:
template<class U> Mallocator(const Mallocator<U>&) noexcept {}
template<class U> bool operator==(const Mallocator<U>&) const noexcept
{
return true;
}
template<class U> bool operator!=(const Mallocator<U>&) const noexcept
{
return false;
}
T* allocate(const size_t n) const;
void deallocate(T* const p, size_t) const noexcept;
};
template <class T>
T* Mallocator<T>::allocate(const size_t n) const
{
if (n == 0)
{
return nullptr;
}
if (n > static_cast<size_t>(-1) / sizeof(T))
{
throw std::bad_array_new_length();
}
void* const pv = malloc(n * sizeof(T));
if (!pv) { throw std::bad_alloc(); }
return static_cast<T*>(pv);
}
template<class T>
void Mallocator<T>::deallocate(T * const p, size_t) const noexcept
{
free(p);
}
typedef unsigned long long uint64_t;
#define COUNT (4*1024*1024-1) // number of values to sort
int main(int argc, char**argv)
{
// this line from a prior answer
// the (0) is needed to prevent compiler error, but changing the
// (0) to (COUNT) or other non-zero value has no effect, the size == 0
std::list <uint64_t, Mallocator<uint64_t>> ll(Mallocator<uint64_t>(0));
// trying to avoid having to resize the list to get an initial size.
ll.resize(COUNT, 0);
I tried some more variations on this which triggered Visual Studio to show various combinations of parameters, and variation 12 of 12 showed the parameters in the correct order: (count, value, allocator). Note in the case of VS 2015, there is no option for (count, allocator), the value needs to be included. The value in the last parameter, <uint64_t>(0), doesn't matter, it just needs to be the proper type.
std::list <uint64_t, Mallocator<uint64_t>> ll(COUNT, 0, Mallocator<uint64_t>(0));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.