Tyl*_*erg 5 c++ allocator c++17
以下是要点:
1:该项目使用开源存储库NanoRT作为项目中的光线追踪器。
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;
Run Code Online (Sandbox Code Playgroud)
我需要弄清楚如何解决这个问题。该错误建议使用std::allocator_traits,但我真的不熟悉std::allocatoror的这种用法allocator_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);
}
Run Code Online (Sandbox Code Playgroud)
有几种方法可以解决这个问题,但一种方法并不适合所有情况。
对于std::allocator<T>,类型std::size_t始终与 相同size_type,并且类型T*始终与 相同pointer。所以最简单的事情就是直接加入这些类型。
std::allocator_traits:这些类型也作为 type 的嵌套类型存在std::allocator_traits<std::allocator<T>>。所以你可以像这样访问它们:
std::allocator_traits<std::allocator<T>>::pointer
Run Code Online (Sandbox Code Playgroud)
创建类型别名来减少冗长是很常见的:
using pointer = std::allocator_traits<std::allocator<T>>::pointer;
Run Code Online (Sandbox Code Playgroud)
Irony: allocator<T>::size_type在 C++20 中“已弃用”。