gpt4 book ai didi

C++:无法使用 scoped_allocator_adaptor 传播 polymorphic_allocator

转载 作者:太空狗 更新时间:2023-10-29 21:32:34 25 4
gpt4 key购买 nike

我有一个 vector<vector<int>>并希望从 memory_resource 中获取整个内存(即外部和内部 vector 的内存) .这是一个精简的例子,首先是无聊的部分:

#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);
}

这给了我一个 lengthy compiler warning ,本质上是说它找不到内部 vector 的构造函数。

如果我不使用多态分配器,而是使用常规分配器(例如,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 会尝试通过两次传递分配器来构造一个 vector ?

此外,here是一个使用 STL(实验性)而不是 boost 的版本。那个给出了一条实际的错误消息“如果 uses_allocator 为真,则必须可以使用分配器进行构造”,但这对我也没有帮助。

也许我在概念上理解错误。这是解决问题的方法还是有更好的方法来解决原来的问题?

最佳答案

唉。解释隐藏在std::experimental::pmr::polymorphic_allocator::construct中:

This function is called (through std::allocator_traits) by any allocator-aware object, such as std::vector, that was given a std::polymorphic_allocator as the allocator to use. Since memory_resource* implicitly converts to polymorphic_allocator, the memory resource pointer will propagate to any allocator-aware subobjects using polymorphic allocators.

事实证明,多态分配器会自动传播。这也解释了为什么分配器在 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?

你不知道。确保所有内部容器也使用多态分配器,然后内存资源将自动传递。

关于C++:无法使用 scoped_allocator_adaptor 传播 polymorphic_allocator,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54654606/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com