以下是关键点:
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::allocator
或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);
}
最佳答案
有两种方法可以解决此问题,并且一个尺寸并不能完全适合所有情况。
最简单的路径:
对于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/