我有一个vector<vector<int>>,并希望从memory_resource中提取整个内存(即外部和内部向量的内存)。下面是一个简化的示例,首先是无聊的部分:
#include <boost/container/pmr/memory_resource.hpp>
#include <boost/container/scoped_allocator.hpp>
#include <boost/container/pmr/polymorphic_allocator.hpp>
#include <iostream>
#include <string>
#include <vector>
// Sample memory resource that prints debug information
class MemoryResource : public boost::container::pmr::memory_resource {
void* do_allocate(std::size_t bytes, std::size_t alignment) {
std::cout << "Allocate " << bytes << " bytes" << std::endl;
return malloc(bytes);
}
void do_deallocate(void* p, std::size_t bytes, std::size_t alignment) { free(p); }
bool do_is_equal(const memory_resource& other) const noexcept { return true; }
};这是我感兴趣的部分:
template <typename T>
using Alloc = boost::container::pmr::polymorphic_allocator<T>;
// using Alloc = std::allocator<T>;
template <typename T>
using PmrVector = std::vector<T, boost::container::scoped_allocator_adaptor<Alloc<T>>>;
using Inner = PmrVector<int>;
int main() {
MemoryResource resource{};
PmrVector<Inner> v(1000, Alloc<Inner>{&resource});
// PmrVector<Inner> v(1337, Alloc<Inner>{});
v[0].resize(100);
}这给了我一个冗长的编译器警告,本质上说它找不到内部向量的构造函数。
如果我使用的不是多态分配器,而是一个常规分配器(例如,std::allocator --参见注释掉的行),那么一切似乎都正常。
gcc的错误信息比clang要好一点:
/usr/local/include/boost/container/allocator_traits.hpp:415:10:
error: no matching function for call to '
std::vector<int, polymorphic_allocator<int> >::vector(
scoped_allocator_adaptor<...>&, polymorphic_allocator<...>&
)
'为什么boost要通过两次传递分配器来构造向量呢?
另外,这里是一个使用STL (实验性)而不是boost的版本。它给出了一个实际的错误消息:“如果uses_allocator是真的话,使用分配器进行构造必须是可能的”,但这也帮不了我。
也许我理解了一些概念上的错误。是这样做的,还是有更好的方法来解决原来的问题?
发布于 2019-02-12 17:35:55
啊。解释隐藏在std::experimental::pmr::polymorphic_allocator::construct中
此函数由任何感知分配器的对象调用(通过std::allocator_traits),如std::std::polymorphic_allocator,该对象被赋予一个std::polymorphic_allocator作为分配器使用。由于memory_resource*隐式转换为polymorphic_allocator,因此内存资源指针将使用多态分配器传播到任何感知分配器的子对象。
因此,多态分配器会自动传播。这也解释了为什么分配程序在gcc错误消息中被传递了两次。
以下是一个工作版本:
template <typename T>
using Alloc = std::experimental::pmr::polymorphic_allocator<T>;
template <typename T>
using PmrVector = std::vector<T, Alloc<T>>;
using Inner = PmrVector<int>;
int main() {
MemoryResource resource{};
PmrVector<Inner> v(1000, Alloc<Inner>{&resource});
v[0].resize(100);
}以下是几个小时前我需要的信息:
如何将polymorphic_allocator和scoped_allocator_adaptor结合使用?
请确保所有内部容器也使用多态分配器,然后内存资源将自动传递。
https://stackoverflow.com/questions/54654606
复制相似问题