如何将scoped_allocator_adaptor与自定义分配器包装在类中一起使用,以便可以对某些类型而不是STL容器进行包装?

如何解决如何将scoped_allocator_adaptor与自定义分配器包装在类中一起使用,以便可以对某些类型而不是STL容器进行包装?

我不知道如何更好地表达我的问题。

我对std::scoped_allocator_adaptor的理解是,它将把分配器实例传递给容器,并将其用于通过emplace_back在容器中构造的元素/容器的构造,如果它们需要这样的分配器的话参数)。

我有以下内容,这有点冗长,但这是我可以做的最低要求,可以说明我正在尝试做的事情:

#include <cstdint>
#include <cstdlib>
#include <memory>
#include <vector>
#include <scoped_allocator>
#include <concepts>

namespace custom_memory
{
    class CustomAllocator
    {
    public:
        CustomAllocator(const std::size_t sizeBytes,void* const start)
        :
            m_sizeBytes(sizeBytes),m_usedBytes(0),m_start(start),m_current(start)
        {

        }

        void* Allocate(const std::size_t& numBytes,const std::uintptr_t& alignment)
        {
            std::size_t space = m_sizeBytes - m_usedBytes;
            if(std::align(alignment,numBytes,m_current,space))
            {
                // the amount used for alignment
                m_usedBytes += (m_sizeBytes-m_usedBytes) - space;
                // the amount actually needed
                m_usedBytes += numBytes;

                void* address = m_current;

                m_current = reinterpret_cast<void*>(
                    reinterpret_cast<std::uintptr_t>(m_current) + numBytes);

                return address;
            }
            throw std::bad_alloc();
        }

        void Free(void* const ptr)
        {
            // do nothing in this Allocator,but other derived types may
        }

        void Clear()
        {
            m_current = m_start;
            m_usedBytes = 0;
        }

        std::size_t GetSize() const { return m_sizeBytes; }

    protected:
        const std::size_t m_sizeBytes;
        std::size_t m_usedBytes;
        void* const m_start;
        void* m_current;
    };
    // many types derive from base CustomAllocator type

    // allows for my custom allocators to be used in STL containers
    template<typename T,typename Alloc>
    class STLAdaptor
    {
    public:

        typedef T value_type;


        STLAdaptor(Alloc* allocator)
        :
            m_allocator(allocator)
        {

        }

        [[nodiscard]] constexpr T* allocate(std::size_t n)
        {
            return reinterpret_cast<T*>
                (m_allocator->Allocate(n * sizeof(T),alignof(T)));
        }

        constexpr void deallocate(T* p,std::size_t n)
        {
            m_allocator->Free(p);
        }

        std::size_t MaxAllocationSize() const
        {
            return m_allocator->GetSize();
        }

    protected:
        Alloc* m_allocator;
    };

    template<typename T,typename Allocator>
    using vector = std::vector<T,std::scoped_allocator_adaptor<STLAdaptor<T,Allocator>>>;
}

// overloads of global new and delete so I can use them with
// my custom allocators
void* operator new(std::size_t size,custom_memory::CustomAllocator& allocator,std::uintptr_t alignment)
{
    return allocator.Allocate(size,alignment);
}

void operator delete(void* ptr,custom_memory::CustomAllocator& allocator)
{
    allocator.Free(ptr);
}

// a type that needs an allocator for it's own internal use
template<typename A>
requires std::derived_from<A,custom_memory::CustomAllocator>
struct Foo
{
    A* m_allocator;
    int* m_foos;

    Foo(A* a)
    :
        m_allocator(a),m_foos(new (*a,alignof(int)) int(7))
    {

    }

    Foo(const Foo<A>& other)
    :
        m_allocator(other.m_allocator),m_foos(new (*m_allocator,alignof(int)) int(*(other.m_foos)))
    {

    }

    ~Foo()
    {
        operator delete (m_foos,*m_allocator);
    }

    Foo<A>& operator=(const Foo<A>& rhs)
    {
        m_allocator = rhs.m_allocator;
        *m_foos = *(rhs.m_foos);

        return *this;
    }
};

int main()
{
    const std::size_t memSize = 10000000;
    void* mem = std::malloc(memSize);

    typedef Foo<custom_memory::CustomAllocator> FooType;

    custom_memory::CustomAllocator customAlloc(memSize,mem);

    // this works
    {
        std::vector<FooType,custom_memory::STLAdaptor<FooType,custom_memory::CustomAllocator>>
            vec(&customAlloc);

        vec.emplace_back(&customAlloc);
    }

    // this works
    {
        custom_memory::vector<FooType,custom_memory::CustomAllocator>
            vec(&customAlloc);

        vec.emplace_back(&customAlloc); // <-- I don't want to pass this
    }

    // this doesn't work
    {
        custom_memory::vector<FooType,custom_memory::CustomAllocator>
            vec(&customAlloc);

        vec.emplace_back(); // <--- I thought scoped_allocator_adaptor
                            // would pass the allocator to constructed
                            // elements?
    }

    // this also doesn't work
    {
        typedef std::basic_string<char,std::char_traits<char>,custom_memory::STLAdaptor<char,custom_memory::CustomAllocator>>
        StringType;

        custom_memory::vector<StringType,custom_memory::CustomAllocator>
            vec(&customAlloc);

        vec.emplace_back("string");
    }

    std::free(mem);

    return 0;
}

我有一个CustomAllocator,它是从一个基数派生的(未显示),并且有一堆从这个基数派生的不同的分配器。

我有一个STLAdaptor,该CustomAllocator可以在STL容器中使用。这是一个模板化类,因为上面提到了许多不同的分配器(实际上,我对不同的分配器也有STLAdaptor的专门知识,未显示)。

我尝试typedef std::vector使用STLAdaptor包裹在CustomAllocator中的std::scoped_allocator_adaptor

然后,我使全局newdelete重载以接受CustomAllocator进行分配。

最后,我有一个需要CustomAllocator的类,在内部它使用它为内部类型分配内存(这是我的用例)。

您可以在我的测试中看到我可以做到:

  1. 制作一个std::vector,成功使用我的STLAdaptor包装的CustomAllocator。我可以用Foo<CustomerAllocator>类型填充它。

  2. 我可以使用std::scoped_allocator_adaptor std::vector的typedef。但是我需要将CustomAllocator实例显式传递给内部类型

  3. 我无法省略,但我想

  4. 我也想使用其他STL容器

我非常确定问题是std::scoped_allocator_adaptor有一个STLAdaptor分配器,而不是CustomAllocator。但是后来我也无法使其与std::string一起使用,但是我认为这与STLAdaptorstd::vector之间具有不同类型的std::string有关(这是rebind发挥作用的地方吗?

我正在使用GCC 10.2.0和C ++ 20

任何帮助将不胜感激。

解决方法

我很确定问题是std::scoped_allocator_adaptor有一个STLAdaptor分配器,而不是CustomAllocator

就目前而言是正确的。 scoped_allocator_adaptor将传递它所拥有的东西,而不是它不知道的其他类型。

此外,scoped_allocator_adaptor将使用uses_allocator来确定类型是否使用分配器。该特征默认是查看该类型是否定义了可以将分配器转换为的成员类型allocator_type

但是后来我也无法使其与std::string一起使用,但是我认为这与STLAdaptor和{{ 1}}(这是std::vector发挥作用的地方吗?

正确。 std::string不符合the allocator requirements

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-
参考1 参考2 解决方案 # 点击安装源 协议选择 http:// 路径填写 mirrors.aliyun.com/centos/8.3.2011/BaseOS/x86_64/os URL类型 软件库URL 其他路径 # 版本 7 mirrors.aliyun.com/centos/7/os/x86
报错1 [root@slave1 data_mocker]# kafka-console-consumer.sh --bootstrap-server slave1:9092 --topic topic_db [2023-12-19 18:31:12,770] WARN [Consumer clie
错误1 # 重写数据 hive (edu)&gt; insert overwrite table dwd_trade_cart_add_inc &gt; select data.id, &gt; data.user_id, &gt; data.course_id, &gt; date_format(
错误1 hive (edu)&gt; insert into huanhuan values(1,&#39;haoge&#39;); Query ID = root_20240110071417_fe1517ad-3607-41f4-bdcf-d00b98ac443e Total jobs = 1
报错1:执行到如下就不执行了,没有显示Successfully registered new MBean. [root@slave1 bin]# /usr/local/software/flume-1.9.0/bin/flume-ng agent -n a1 -c /usr/local/softwa
虚拟及没有启动任何服务器查看jps会显示jps,如果没有显示任何东西 [root@slave2 ~]# jps 9647 Jps 解决方案 # 进入/tmp查看 [root@slave1 dfs]# cd /tmp [root@slave1 tmp]# ll 总用量 48 drwxr-xr-x. 2
报错1 hive&gt; show databases; OK Failed with exception java.io.IOException:java.lang.RuntimeException: Error in configuring object Time taken: 0.474 se
报错1 [root@localhost ~]# vim -bash: vim: 未找到命令 安装vim yum -y install vim* # 查看是否安装成功 [root@hadoop01 hadoop]# rpm -qa |grep vim vim-X11-7.4.629-8.el7_9.x
修改hadoop配置 vi /usr/local/software/hadoop-2.9.2/etc/hadoop/yarn-site.xml # 添加如下 &lt;configuration&gt; &lt;property&gt; &lt;name&gt;yarn.nodemanager.res