This page is a snapshot from the LWG issues list, see theLibrary Active Issues List for more information and the meaning ofC++20 status.
Section: 20.5.3.3[mem.poly.allocator.mem]Status:C++20Submitter: Casey CarterOpened: 2019-07-18Last modified: 2021-02-25
Priority:2
View all otherissues in [mem.poly.allocator.mem].
View all issues withC++20 status.
Discussion:
Both LWG3038(i) and LWG3190(i) deal with how to respond to requests to allocate "n * sizeof(T)" bytes of memory whenn * sizeof(T) is not sufficient storage forn objects of typeT, i.e., whenn > SIZE_MAX / sizeof(T). LWG3038(i) changedpolymorphic_allocator::allocate to throwlength_error upon detecting this condition, whereas LWG3190(i) changedallocator::allocate to throwbad_array_new_length. It's peculiar that two standard library components which allocate memory both detect this condition but handle it by throwing different exception types; for consistency, the two should be harmonized.
bad_array_new_length was the better option. Unlikelength_error,bad_array_new_length derives frombad_alloc so we can make this change without altering the invariant that allocation functions either succeed or throw an exception derived frombad_alloc.Further,P0339R6 "polymorphic_allocator<> as a vocabulary type" recently added the function template "template<class T> T* allocate_object(size_t n = 1);" tostd::pmr::polymorphic_allocator, which is another instance of the "allocate memory forn objects of typeT" pattern. 20.5.3.3[mem.poly.allocator.mem] paragraph 8.1 specifies thatallocate_object throwslength_error whenSIZE_MAX / sizeof(T) < n, presumably for consistency withstd::pmr::polymorphic_allocator::allocate specified in paragraph 1.allocate_object's behavior should be consistent withallocator::allocate andpolymorphic_allocator::allocate so we have a single means of communicating "request for allocation of unrepresentable size" errors in the Standard Library.[2020-02 Moved to Immediate on Thursday afternoon in Prague.]
Proposed resolution:
This wording is relative toN4820.
Modify 20.5.3.3[mem.poly.allocator.mem] as indicated:
[[nodiscard]] Tp* allocate(size_t n);[…]-1-Effects: If
SIZE_MAX / sizeof(Tp) < n, throws. Otherwise equivalent to:length_errorbad_array_new_lengthreturn static_cast<Tp*>(memory_rsrc->allocate(n * sizeof(Tp), alignof(Tp)));template<class T> T* allocate_object(size_t n = 1);-8-Effects: Allocates memory suitable for holding an array of
nobjects of typeT, as follows:
(8.1) — if
SIZE_MAX / sizeof(T) < n, throws,length_errorbad_array_new_length(8.2) — otherwise equivalent to:
return static_cast<T*>(allocate_bytes(n*sizeof(T), alignof(T)));