当使用 C++17 多态分配器和 set/get_default_resource 方法时(参见 https://en.cppreference.com/w/cpp/memory/set_default_resource),所有资源都通过指针传递/返回,而使用 nullptr 几乎没有意义,而且感觉它可以大部分时间作为引用(如果需要,然后存储为 ref_wrapper)。
这有什么逻辑/风格上的原因吗?
最佳答案
正如您链接的页面所引用的那样,set_default_resource()
确实接受一个空指针并且在这种情况下具有特定的行为:
If
r
is not null, sets the default memory resource pointer tor
; otherwise, sets the default memory resource pointer tostd::pmr::new_delete_resource()
.
初始论文,N3525 , 也引用了理由:
We have found it is convenient to use
nullptr
as a surrogate for the “default-default” handler in various interfaces. The use here simply provides consistency and makes it easy to reset the default resource to its initial state.
和后续修订,N3916 , 状态:
Note that the memory-resource library is designed so that the
ShoppingList
constructor accepts a pointer to amemory_resource
rather than a reference to amemory_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).
关于c++ - 为什么 set/get_default_resource 使用指针而不是引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57793907/