根据@BenVoigt的建议,为了回答我关于堆栈分配字符串流存储的问题,我设计了一个stack_allocator(代码如下(,并使用它声明了一个basic_ostringstream类型。
不过,我遇到了一个奇怪的错误。当我打印生成的字符串时,我放入流中的第一个字符被省略了!
下面是一个示例:
template<typename T, size_t capacity, size_t arr_size>
__thread bool stack_allocator<T, capacity, arr_size>::_used[arr_size] = {};
template<typename T, size_t capacity, size_t arr_size>
__thread T stack_allocator<T, capacity, arr_size>::_buf[capacity][arr_size] = {};
typedef std::basic_ostringstream<char,
std::char_traits<char>,
stack_allocator<char, 1024, 5> > stack_ostringstream;
int main()
{
stack_ostringstream _os;
_os << "hello world";
std::cout << _os.str() << std::endl;
return 0;
}
生成的输出为:
埃洛世界
谁能详细说明第一个角色发生了什么?
stack_allocator如下:它非常简单,我相信还有很大的改进空间(无法修复错误!
#include <cstddef>
#include <limits>
#include <bits/allocator.h>
template<typename T, size_t capacity = 1024, size_t arr_size = 5>
class stack_allocator
{
public:
typedef T value_type;
typedef value_type* pointer;
typedef const value_type* const_pointer;
typedef value_type& reference;
typedef const value_type& const_reference;
typedef std::size_t size_type;
typedef std::ptrdiff_t difference_type;
inline explicit stack_allocator() { }
template<typename U>
inline explicit stack_allocator(const stack_allocator<U, capacity, arr_size>& that) { }
inline ~stack_allocator() {}
template<typename U>
struct rebind
{
typedef stack_allocator<U, capacity, arr_size> other;
};
inline pointer allocate(size_type cnt, typename std::allocator<void>::const_pointer = 0)
{
if (cnt > capacity)
return reinterpret_cast<pointer>(::operator new(cnt * sizeof (T)));
for (size_t i = 0; i < arr_size; ++i)
{
if (!_used[i])
{
_used[i] = true;
return reinterpret_cast<pointer>(_buf[i]);
}
}
}
inline void deallocate(pointer p, size_type)
{
for (size_t i = 0; i < arr_size; ++i)
{
if (p != _buf[i])
continue;
_used[i] = false;
return;
}
::operator delete(p);
}
inline pointer address(reference r) { return &r; }
inline const_pointer address(const_reference r) { return &r; }
inline size_type max_size() const
{
return std::numeric_limits<size_type>::max() / sizeof(T);
}
inline void construct(pointer p, const T& t) { new(p) T(t); }
inline void destroy(pointer p) { p->~T(); }
inline bool operator==(const stack_allocator&) const { return true; }
inline bool operator!=(const stack_allocator& a) const { return !operator==(a); }
private:
static __thread bool _used[arr_size];
static __thread T _buf[capacity][arr_size];
};
如果分配的项目超过 arr_size
,您的allocate
函数可能会掉落。如果你使用g++ -Wall
它会警告你这些事情。
另一个问题是您的_buf
数组索引是向后的。它应该是static T _buf[arr_size][capacity];
,它将arr_size
作为行,而不是您在原始代码中具有它的其他顺序,这使得容量成为第一个索引。
另外作为旁注,只需避免使用以前导标识符开头的标识符_
因为某些此类标识符是为实现保留的,并且从不使用它们比记住确切的规则更容易。最后,切勿直接包含bits/
标头,只需使用真正的标头。在这种情况下,memory
.我还必须为<iostream>
添加包含,并<sstream>
才能编译它。