c++ - 如何解决std::allocator的不推荐使用?

标签 c++ c++17 allocator

以下是关键点:
1:该项目使用开源资源库NanoRT作为项目中的raytracer。
2:此项目在Visual Studio 2019(C++ 17)下编译
3:编译该项目时,会将警告视为错误(并且无法更改)。添加定义以禁止显示这些警告没有帮助。
但是,看起来该代码的一部分在C++ 17中不起作用,因为它使用了已被弃用的内容:(我提供的链接中的第133和134行)

  typedef typename std::allocator<T>::pointer pointer;
  typedef typename std::allocator<T>::size_type size_type;
我需要弄清楚如何解决此问题。该错误提示您使用std::allocator_traits,但是我真的不熟悉std::allocatorallocator_traits的这种用法。
从源头上看,这是几行修复,还是比这复杂得多,并且需要重组大部分代码?
看起来pointer用作allocate()的返回值和deallocate()的第一个参数,而size_type的使用方式相同。
  // Actually do the allocation. Use the stack buffer if nobody has used it yet
  // and the size requested fits. Otherwise, fall through to the standard
  // allocator.
  pointer allocate(size_type n, void *hint = 0) {
    if (source_ != NULL && !source_->used_stack_buffer_ &&
        n <= stack_capacity) {
      source_->used_stack_buffer_ = true;
      return source_->stack_buffer();
    } else {
      return std::allocator<T>::allocate(n, hint);
    }
  }

  // Free: when trying to free the stack buffer, just mark it as free. For
  // non-stack-buffer pointers, just fall though to the standard allocator.
  void deallocate(pointer p, size_type n) {
    if (source_ != NULL && p == source_->stack_buffer())
      source_->used_stack_buffer_ = false;
    else
      std::allocator<T>::deallocate(p, n);
  }

最佳答案

有两种方法可以解决此问题,并且一个尺寸并不能完全适合所有情况。
最简单的路径:
对于std::allocator<T>,类型std::size_t始终与size_type相同,并且类型T*始终与pointer相同。因此,最简单的方法就是将这些类型归为一类。std::allocator_traits路径:
这些类型也以std::allocator_traits<std::allocator<T>>类型的嵌套类型存在。因此,您可以像这样访问它们:

std::allocator_traits<std::allocator<T>>::pointer
创建类型别名以减少冗长是很常见的:
using pointer = std::allocator_traits<std::allocator<T>>::pointer;

具有讽刺意味的是:allocator<T>::size_type在C++ 20中被“弃用”。

关于c++ - 如何解决std::allocator的不推荐使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62682216/

相关文章:

分析内存分配器的正确方法

C++ Placement new 和构造函数调用

c++ - 为什么我会收到此 'redeclared as different kind of symbol' 错误?

c++ - Qt:单击后开始编辑单元格

c++ - 获取错误无法从C++ 17编译器的间接库继承构造函数

c++ - 当目标指针不是基类的类型时,为什么允许dynamic_cast为多态类生成空指针?

c++ - 带有自定义分配器的 std::vector 子类与 std::vectors 之间的转换

c++ - 你能用 memcpy 反序列化字节吗?

c++ - 如何通过点和法线获取平面顶点

c++ - Clang claims that `member reference base type ' X' is not a structure or union`,但 X 是具有推导参数的结构模板