Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does `polymorphic_allocator` take a `memory_resource` pointer and not a reference?

The C++17 Standard says:

[mem.poly.allocator.ctor]

polymorphic_allocator(memory_resource* r);
  • Requires: r is non-null.

  • Effects: Sets memory_­rsrc to r.

  • Throws: Nothing.

  • [ Note: This constructor provides an implicit conversion from memory_­resource*. — end note ]

What's the point of accepting a memory_resource* instead of a memory_resource& if the "requires" clause mentions that r must be non-null?

The Bloomberg¹ style guide encourages accepting arguments that are going to be mutated by pointer instead of reference so that the ampersand on the caller side becomes a visual marker for mutation. However, there is no such precedent in the Standard.

What is the reason that r is taken as a pointer and not as a reference?


¹ pmr was standardized with heavy Bloomberg participation, as the company uses a polymorphic allocator model.

like image 249
Vittorio Romeo Avatar asked May 06 '19 23:05

Vittorio Romeo


1 Answers

N3916:

Note that the memory-resource library is designed so that the ShoppingList constructor accepts a pointer to a memory_resource rather than a reference to a memory_resource. It was noted that one common practice is to use references rather than pointers in situations where a null pointer is out of contract. However, there is a more compelling practice of avoiding constructors that take objects by reference and store their addresses. We also want to avoid passing non-const references, as that, too, is usually considered bad practice (except in overloaded operators).

like image 197
Language Lawyer Avatar answered Jan 03 '23 13:01

Language Lawyer