简体   繁体   English

shared_ptr <>到数组自定义删除器(使用make_shared)

[英]shared_ptr<> to an array custom deleter (with make_shared)

Is it possible to use make_shared and a custom deleter for an array that a shared_ptr<> points to (below is the way I tried doing it via the constructor, but I have no idea how that would work via using make_shared)? 是否可以对shared_ptr <>指向的数组使用make_shared和自定义删除器(下面是我尝试通过构造函数执行此操作的方式,但我不知道如何通过使用make_shared工作)?

int n = 5;
shared_ptr<int> a(new int[n], default_delete<int[]>());

What I would like to make it look like is something similar to this, but with allocating memory for an int array and also having a custom deleter. 我想让它看起来像是类似的东西,但是为int数组分配内存并且还有一个自定义删除器。 Is that possible? 那可能吗?

int n = 5;
shared_ptr<int> a;
a = make_shared<int>();

Unfortunately there is no way to specify a custom deleter as of right now with std::make_shared , you could however, make a wrapper around make_shared if you want 不幸的是,现在无法使用std::make_shared指定自定义删除器,但是如果需要,可以在make_shared周围创建一个包装器

( a little less efficient , but ¯\\_(ツ)_/¯) 效率稍低,但是¯\\ _(ツ)_ /¯)

template <typename Type, typename Deleter, typename... Args>
auto make_shared_deleter(Deleter&& deleter, Args&&... args) {
    auto u_ptr = std::make_unique<Type>(std::forward<Args>(args)...);
    auto with_deleter = std::shared_ptr<Type>{
        u_ptr.release(), std::forward<Deleter>(deleter)};
    return with_deleter;
}

And then use it like so 然后像这样使用它

int main() {
    auto ptr = make_shared_deleter<int>(std::default_delete<int>(), 1);
    cout << *ptr << endl;
}

If you just want to use a shared_ptr and have it point to an array, see shared_ptr to an array : should it be used? 如果您只想使用shared_ptr并将其指向数组,请参阅shared_ptr到数组:是否应该使用它? for more 更多

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM