admin管理员组文章数量:1123056
I have implemented a custom allocator that takes a block of memory from the stack and allocates linearly out of it, ignoring calls to deallocate. This is used with a std::map to improve performance in a tight loop.
template <typename T>
struct region_allocator
{
using value_type = T;
region_allocator() = delete;
region_allocator( void* baseAddress, size_t sizeInBytes )
{
m_memBegin = (char*)baseAddress;
m_memCurr = m_memBegin;
m_memEnd = m_memCurr + sizeInBytes;
}
template <class U>
constexpr region_allocator( const region_allocator<U>& other ) noexcept
{
m_memBegin = other.m_memBegin;
m_memCurr = other.m_memCurr;
m_memEnd = other.m_memEnd;
}
template <class U>
struct rebind
{
using other = region_allocator<U>;
};
T* allocate( std::size_t n )
{
char* address = m_memCurr;
size_t sizeRequired = sizeof( T ) * n;
m_memCurr += sizeRequired;
if( m_memCurr > m_memEnd ) [[unlikely]]
{
m_memCurr -= sizeRequired;
assert( "Out of memory" );
}
return (T*)address;
}
void deallocate( T* p, std::size_t n ) noexcept
{
// don't free; caller will release full block
}
protected:
template <class U>
friend struct region_allocator;
char* m_memCurr = nullptr;
char* m_memEnd = nullptr;
char* m_memBegin = nullptr;
};
template <class T, class U>
bool operator==( const region_allocator<T>& lhs, const region_allocator<U>& rhs ) noexcept
{
if( lhs.m_memBegin != rhs.m_memBegin )
return false;
if( lhs.m_memEnd != rhs.m_memEnd )
return false;
return true;
}
Regardless of whether this is the best algorithmic solution, the problem I am encountering is that the allocator is copied by value during the rebind operation, and state is copied, and the original allocator instance passed in does not see the changes in state as allocations are made.
I understand that allocators are copied by value. I see that what I want to do is hold onto a shared instance of the allocator state (current offset into the block of memory), but I am not clear on the best pattern to do that.
What pattern do others use for this problem?
本文标签: cGiven that allocators are copied by value how is allocator state sharedStack Overflow
版权声明:本文标题:c++ - Given that allocators are copied by value how is allocator state shared? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1736543221a1944413.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论