c++ - C++11 兼容的线性分配器实现
问题描述
我已经实现了一个 C++11 兼容的线性或竞技场分配器。代码如下。
线性分配器.hpp:
#pragma once
#include <cstddef>
#include <cassert>
#include <new>
#include "aligned_mallocations.hpp"
template <typename T>
class LinearAllocator
{
public:
using value_type = T;
using pointer = T*;
using const_pointer = const T*;
using reference = T&;
using const_reference = const T&;
//using propagate_on_container_copy_assignment = std::true_type;
//using propagate_on_container_move_assignment = std::true_type;
//using propagate_on_container_swap = std::true_type;
LinearAllocator(std::size_t count = 64)
: m_memUsed(0),
m_memStartAddress(nullptr)
{
allocate(count);
}
~LinearAllocator()
{
clear();
}
template <class U>
LinearAllocator(const LinearAllocator<U>&) noexcept
{}
/// \brief allocates memory equal to # count objects of type T
pointer allocate(std::size_t count)
{
if (count > std::size_t(-1) / sizeof(T))
{
throw std::bad_alloc{};
}
if (m_memStartAddress != nullptr)
{
alignedFree(m_memStartAddress);
}
m_memUsed = count * sizeof(T);
m_memStartAddress = static_cast<pointer>(alignedMalloc(m_memUsed, alignof(T)));
return m_memStartAddress;
}
/// \brief deallocates previously allocated memory
/// \brief Linear/arena allocators do not support free() operations. Use clear() instead.
void deallocate([[maybe_unused]] pointer p, [[maybe_unused]] std::size_t count) noexcept
{
//assert(false);
clear();
}
/// \brief simply resets memory
void clear()
{
if (m_memStartAddress != nullptr)
{
alignedFree(m_memStartAddress);
m_memStartAddress = nullptr;
}
this->m_memUsed = 0;
}
/// \brief GETTERS
pointer getStartAddress() const
{
return this->m_memStartAddress;
}
std::size_t getUsedMemory() const
{
return this->m_memUsed;
}
private:
std::size_t m_memUsed;
pointer m_memStartAddress;
};
template <class T, class U>
bool operator==(const LinearAllocator<T> &, const LinearAllocator<U> &)
{
return true;
}
template <class T, class U>
bool operator!=(const LinearAllocator<T> &, const LinearAllocator<U> &)
{
return false;
}
不要担心alignedMalloc
和alignedFree
。他们是正确的。
这是我的测试程序(linear_allocator.cpp):
#include "linear_allocator.hpp"
#include <vector>
#include <deque>
#include <iostream>
#include <string>
#include <typeinfo>
int main()
{
[[maybe_unused]]
LinearAllocator<int> a{1024};
std::cout << a.getStartAddress() << '\n';
std::cout << a.getUsedMemory() << '\n';
std::vector<std::string, LinearAllocator<std::string>> v;
v.reserve(100);
std::cout << "Vector capacity = " << v.capacity() << '\n';
//std::cout << v.get_allocator().getStartAddress() << '\n';
//std::cout << v.get_allocator().getUsedMemory() << '\n';
v.push_back("Hello");
v.push_back("w/e");
v.push_back("whatever");
v.push_back("there is ist sofi j");
v.push_back("wisdom");
v.push_back("fear");
v.push_back("there's more than meets the eye");
for (const auto &s : v)
{
std::cout << s << '\n';
}
std::cout << typeid(v.get_allocator()).name() << '\n';
std::deque<int, LinearAllocator<int>> dq;
dq.push_back(23);
dq.push_back(90);
dq.push_back(38794);
dq.push_back(7);
dq.push_back(0);
dq.push_back(2);
dq.push_back(13);
dq.push_back(24323);
dq.push_back(0);
dq.push_back(1234);
for (const auto &i : dq)
{
std::cout << i << '\n';
}
std::cout << typeid(dq.get_allocator()).name() << '\n';
}
编译g++ -std=c++17 -O2 -march=native -Wall linear_allocator.cpp -o linear_allocator.gpp.exe
并运行 linear_allocator.gpp.exe 给出输出:
0x4328b8
4096
Vector capacity = 100
Hello
w/e
whatever
there is ist sofi j
wisdom
fear
there's more than meets the eye
15LinearAllocatorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEE
如您所见,deque 的输出根本不存在。如果我取消注释这两行:
//std::cout << v.get_allocator().getStartAddress() << '\n';
//std::cout << v.get_allocator().getUsedMemory() << '\n';
矢量的输出也不会显示。
用 MSVS cl 编译得到以下输出:
000000B47A1CAF88
4096
更糟糕的是。
因为似乎有 UB,所以我必须缺少一些东西,但我无法确定它在哪里。我的分配器设计基于 C++11 + 指南。我想知道我做错了什么。
解决方案
虽然分配器负责提供和释放用于存储容器数据的内存,但它仍然只在容器请求时才这样做。也就是说,提供的存储(特别是它的生命周期)的实际管理仍然在容器方面。想象一下当向量执行其元素的重定位时会发生什么:
请求比当前(旧)内存大给定因子的新内存块。
存储在“旧”块中的元素被复制/移动到新块中。
只有这样,“旧”内存块才能被释放。
在您的实现中,一次只能有一个内存块处于活动状态——旧的内存块在分配新的内存块之前被释放(特别是,当容器只请求一个新的内存块时,就会发生这种情况,其中元素可能是迁至)。当向量试图从以前的存储中重新定位元素时,您已经调用了 UB,因为它们所在的内存已经失效。
此外,通过不为分配器类型提供复制构造函数,编译器提供的实现执行浅拷贝(即,它复制指针,而不是存储在该地址下的数据),然后在析构函数中释放。也就是说,调用:
v.get_allocator()
将制作分配器的浅拷贝,创建分配器类型的纯右值,并在临时对象结束其生命周期后立即释放存储的指针(即,在包含cout
调用的完整语句结束时),导致双重调用在alignedFree
同一个指针上。
推荐阅读
- ios - 为什么会在没有调用 setActive: 的情况下激活自动布局约束?
- php - PHP TCPDF 在 ubuntu 14.04 上永久移动错误
- gradle - 无法为 org.gradle.api.internal.tasks.DefaultSourceSetContainer 类型的 SourceSet 容器上的参数找到方法 srcDirs()
- javascript - 如何在 JavaScript 中使用 $.getJSON 来检索 python 文件数据?
- matlab - 改变matlab中的输出顺序
- python - 使用 Pickle 在 Python 中进行套接字编程
- php - 无法获取将信用卡信息插入数据库的 PHP 代码
- scala - “用户未初始化火花上下文”在 SPARK YARN 集群模式下使用 Scala 代码时出错
- python - 正则化逻辑回归低准确率
- mysql - Ansible playbook 错误:无法在路径中找到所需的可执行 mysql