我不太了解C ++ 11中的allocator_traits,所以我尝试了cpluspluswebsite中的allocator_traits exmple。但是,此代码无法在gcc 4.9,VS 2015中编译,甚至不能在自己的网站中编译。
还有什么,我也不明白为什么在这个例子中我看不到任何allocator_traits语法。我可以看到这个例子构建一个自定义分配器,然后在向量中使用allocator。没有关于allocator_traits的信息。
任何人都可以帮助我吗?
// custom allocator example
#include <cstddef>
#include <iostream>
#include <memory>
#include <vector>
template <class T>
struct custom_allocator {
typedef T value_type;
custom_allocator() noexcept {}
template <class U> custom_allocator (const custom_allocator<U>&) noexcept {}
T* allocate (std::size_t n) { return static_cast<T*>(::new(n*sizeof(T))); }
void deallocate (T* p, std::size_t n) { ::delete(p); }
};
template <class T, class U>
constexpr bool operator== (const custom_allocator<T>&, const custom_allocator<U>&) noexcept
{return true;}
template <class T, class U>
constexpr bool operator!= (const custom_allocator<T>&, const custom_allocator<U>&) noexcept
{return false;}
int main () {
std::vector<int,custom_allocator<int>> foo = {10,20,30};
for (auto x: foo) std::cout << x << " ";
std::cout << '\n';
return 0;
}
cplusplus网站中的编译错误是:
In member function 'T* custom_allocator<T>::allocate(std::size_t)':
12:74: error: expected type-specifier before ')' token
In instantiation of 'T* custom_allocator<T>::allocate(std::size_t) [with T = int; std::size_t = long unsigned int]':
/usr/include/c++/4.9/bits/alloc_traits.h:357:32: required from 'static std::allocator_traits<_Alloc>::pointer std::allocator_traits<_Alloc>::allocate(_Alloc&, std::allocator_traits<_Alloc>::size_type) [with _Alloc = custom_allocator<int>; std::allocator_traits<_Alloc>::pointer = int*; std::allocator_traits<_Alloc>::size_type = long unsigned int]'
/usr/include/c++/4.9/bits/stl_vector.h:170:46: required from 'std::_Vector_base<_Tp, _Alloc>::pointer std::_Vector_base<_Tp, _Alloc>::_M_allocate(std::size_t) [with _Tp = int; _Alloc = custom_allocator<int>; std::_Vector_base<_Tp, _Alloc>::pointer = int*; std::size_t = long unsigned int]'
/usr/include/c++/4.9/bits/stl_vector.h:1287:27: required from 'void std::vector<_Tp, _Alloc>::_M_range_initialize(_ForwardIterator, _ForwardIterator, std::forward_iterator_tag) [with _ForwardIterator = const int*; _Tp = int; _Alloc = custom_allocator<int>]'
/usr/include/c++/4.9/bits/stl_vector.h:378:36: required from 'std::vector<_Tp, _Alloc>::vector(std::initializer_list<_Tp>, const allocator_type&) [with _Tp = int; _Alloc = custom_allocator<int>; std::vector<_Tp, _Alloc>::allocator_type = custom_allocator<int>]'
25:57: required from here
12:77: warning: no return statement in function returning non-void [-Wreturn-type]
gcc 4.9报告类似的错误。
VS 2015在第12行报告错误。消息如下:
Severity Code Description Project File Line Suppression State
Error C2059 syntax error: ')' allocator_traits c:\users\jiang\documents\visual studio 2015\projects\allocator_traits\allocator_traits.cpp 12
答案 0 :(得分:2)
将::operator new
替换为operator new
,它会起作用。可能是网站上的拼写错误。您在这里呼叫new
,而不是调用{{1}}表达式。