具有std :: function的std :: shared_ptr作为自定义删除器和分配器

时间:2019-12-06 09:04:04

标签: c++ c++14 shared-ptr std-function

有没有办法使这项工作成功?

#include <functional>
#include <memory>
int main()
{
    std::function<unsigned char*(size_t)> allocator 
    = [](size_t size){
        return new unsigned char[size];
    };    
    std::function<void(unsigned char*)> deleter 
    = [](unsigned char* ptr){
        delete[] ptr;
    };
    std::shared_ptr<unsigned char[]> mem(size_t,deleter,allocator);
    return EXIT_SUCCESS;
}

我得到了错误:

main.cpp: In function ‘int main()’:
main.cpp:15:49: error: ‘deleter’ is not a type
     std::shared_ptr<unsigned char[]> mem(size_t,deleter,allocator);
                                                 ^~~~~~~
main.cpp:15:57: error: ‘allocator’ is not a type
     std::shared_ptr<unsigned char[]> mem(size_t,deleter,allocator);
                                                         ^~~~~~~~~

更多背景信息:

我有模板类,其中包含一些内存。这是通过shared_ptr完成的,后者是使用自定义的分配器和删除器创建的。分配器和删除器不是该类的模板参数。

我现在想向类添加一个调整大小的方法。我想避免提供新的Allocator和Delter并将其保存在std::function中。

1 个答案:

答案 0 :(得分:1)

分配器不应该处理您的数据分配,它应该处理shared_ptr内部数据的分配。

您需要将已分配的数据作为第一个参数提供给构造函数。 shared_ptr只负责清理内存。

此外,shared_ptr的模板参数必须为类型而没有间接。

#include <functional>
#include <memory>
int main()
{
    std::function<void(unsigned char*)> deleter 
    = [](unsigned char* ptr){
        delete[] ptr;
    };
    std::shared_ptr<unsigned char> mem(new unsigned char[5], deleter);
    return EXIT_SUCCESS;
}

如果可以的话,您应该首选Lambda而不是std::function,这使编译器可以进行优化。