Standard compatible custom dispenser

Is it possible to throw an exception when 0 is passed to the allocate method?

Thanks.

PS

If n == 0, the return value is not undefined.

Does this mean that allocate should not throw an exception? I am inclined to think that if the throw was not allowed for n == 0, then the standard would clearly designate it.

+7
source share
2 answers

The whole standard should say (Β§20.1.5 / 2) that this

  • T - any type
  • X - Allocator class for type T
  • a is a value of type X&
  • n - value of type X::size_type ,

the return value of the expression a.allocate(n) not specified if n is 0.

One hand, given that X::allocate does not have any specification of specified exceptions and can explicitly throw std::bad_alloc , I don’t understand why it cannot throw any other type of exception either. On the other hand, the wording specifically causes a condition in which n is zero and directly implies that there is a return value, that is, you should not throw. I think that it may be open to some kind of interpretation, but personally I would join the latter and consider it an exceptional code.

+7
source

The standard requires that a size distribution of 0 return a pointer to a byte-sized block of memory 1 , Brb, looking for an appropriate paragraph of standards.


Edit :
Firstly, I only got FDIS from C ++ 0x / 11 (not at home ...), but I believe that the wording was similar in C ++ 98/03.

Then, it seems, I was mistaken. Nowhere is it indicated that the allocator should return a memory block of size 1 . My memory helped me make a mistake. :( Although, I found this little paragraph in section 3.7.4.2 [basic.stc.dynamic.allocation] p2:

Even if the size of the requested space is zero, the request may fail. If the request succeeds, the return value must be a non-zero pointer value (4.10) p0 other than any previously returned p1 value, unless that p1 value was subsequently passed to the operator deletion. The dereferencing effect of a pointer returned as a zero-size query is undefined. 35)

At the end of the same site:

35) . The goal is to implement the new () operator by calling std :: malloc () or std :: calloc (), so the rules are basically the same. C ++ differs from C in the requirement of a null request to return a non-null pointer.

(Emphasize mine.)

Now FDIS says in 17.6.3.5 [allocator.requirements] in a note on allocate :

 a.allocate(n) X::pointer 

Memory is allocated for n objects of type T , but no objects are created. allocate may raise a corresponding exception. [Note: if n == 0, the return value is not specified. -end note]

(My emphasis.)
So you should not give up, as the return of something is implied by this note. However, it is not necessary to return a 1 byte memory block. So, to answer your question: No, you are not allowed to throw allocate when the request is size 0 when implementing a standard compatible dispenser.

+6
source

All Articles