简体   繁体   English

有没有一种标准方法可以使用自定义析构函数创建可共享对象?

[英]Is there a standard way to create a sharable objects with a custom destructor?

Is there a standard type that looks like a std::shared_ptr in all aspects except actually pointing to anything?除了实际指向任何东西之外,是否存在在所有方面看起来像std::shared_ptr的标准类型?

I'm looking for something that's copyable/movable, typesafe, ref-counted, easily constructible with a custom deleter.我正在寻找可复制/可移动、类型安全、引用计数、易于使用自定义删除器构建的东西。

I just don't need it to point to anything.我只是不需要它指向任何东西。

I have been using std::make_shared((int*)1, [](auto) { /* do stuff */ }) , but I really don't need the int .我一直在使用std::make_shared((int*)1, [](auto) { /* do stuff */ }) ,但我真的不需要int Maybe I'm missing something, but I see overly-verbose boilerplate all over the place for doing precisely this.也许我遗漏了一些东西,但我看到到处都是过于冗长的样板文件来精确地做到这一点。

How about this?这个怎么样? Same use of a shared_ptr that doesn't point to anything but with a custom constructor that takes any function (with no arguments).同样使用 shared_ptr,它不指向任何东西,只是带有一个接受任何 function(不带参数)的自定义构造函数。

class shared_destructible : public std::shared_ptr<void> {
public:
    template<typename F, typename = std::enable_if_t<std::is_invocable_v<F>>>
    shared_destructible(F f): std::shared_ptr<void>(nullptr, [f](void*){
        f();
    }) {}
};

Example use使用示例

int main() {
    int test = 2023;
    shared_destructible a([test]() { std::cout << test << std::endl; });
    auto b = a;
    auto c = a;
    return 0;
}

Output: Output:

2023

std::shared_ptr can give you the "shared" part, and you can write your own custom class for the destruction part. std::shared_ptr可以为您提供“共享”部分,您可以为销毁部分编写自己的自定义 class。 In full generality (if you want the lambda parameter like in your example),完全通用(如果您想要 lambda 参数,就像您的示例中那样),

class Destructible {
private:
  std::function<void()> impl;
public:
  Destructible(const std::function<void()>& impl) : impl(impl) {}
  ~Destructible() {
    impl();
  }
};

Then the type you're looking for is called std::shared_ptr<Destructible> .那么您要查找的类型称为std::shared_ptr<Destructible> You can construct one with std::make_shared<Destructible>([]() {... });您可以使用std::make_shared<Destructible>([]() {... });构建一个

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

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