c++ - 为什么 set/get_default_resource 使用指针而不是引用?

标签 c++ pointers reference c++17

当使用 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 to r; otherwise, sets the default memory resource pointer to std::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 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).

关于c++ - 为什么 set/get_default_resource 使用指针而不是引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57793907/

相关文章:

c++ - 编译器显示错误消息 "makes pointer from integer without cast"(反转数组)。我该如何解决这个问题?

c++ - 单例日志类中运算符 << 的问题

c# - 将 C 结构与 union 编码到 C# 代码时获取垃圾数据

c - C语言中多维数组指针的工作原理

c++ - 运算符(operator)的评价顺序 *

C++ vector 问题;通过引用传递东西

.NET 在多个解决方案中查找死代码

c++ - 为什么我的程序输出中有空格?

c++ - 取消引用的 InputIterator 的地址? istream_iterator 的案例

pointers - 为什么接口(interface)类型不提供 "IsNil"方法?