c++ - 如何关闭标准智能指针的自定义删除功能?

标签 c++ c++17 std

我介绍了一个FreeGuard类,如果初始化失败,它会清理资源:

struct Resource {...};

class FreeGuard {
public:
    FreeGuard(Resource* r) : resource(r) {};
    ~FreeGuard() {
        if (!dismissed) {
            freeResource(resource);
        }
    }
    void dismiss() { dismissed = true; }

private:
    bool dismissed = false;
    Resource* resource;
};

int init(Resource* r) {
    FreeGuard guard(r);
    if (...)
        return -1;
    if (...)
        return -2;
    ...
    if (...)
        return -1000;
    guard.dismiss();
    return 0;
}

int freeResource(Resource* r) {...}
如何使用std智能指针实现相同目的,从而不必继续编写FreeGuard类?

最佳答案

您可以使用release()unique_ptr函数。当处理非RAII资源(例如C库句柄)时,这是异常安全代码的常见模式:

#include <memory>

int freeResource(Resource* r) {...}

int init(Resource* r) {
    std::unique_ptr<Resource, decltype(&freeResource)> guard(r, freeResource);
    if (...)
        return -1;
    if (...)
        return -2;
    ...
    if (...)
        return -1000;
    guard.release(); // releases ownership, deleter will not be called
    return 0;
}
只需将free()函数重命名为其他名称(此处为freeResource()),以避免与标准free()函数冲突。

关于c++ - 如何关闭标准智能指针的自定义删除功能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63914784/

相关文章:

c++ - 运行 C++ 应用程序后出现 SQLite 控制台

c++ - 为什么(或何时)模板引入其命名空间?

c++ - <chrono> 错误太多 (std::chrono::timepoint) (VS2015)

c++ - C++ 中不同 vector 之间没有线程安全?

c++ - 可以在linux程序中使用带有msvc的在windows上构建的lib

c++ - 如何从 C++ 中的 Base64 编码字符串在 GDI+ 中创建图像?

c++ - 如何在 C++ 中的多个对象中使用通用值?

c++ - 更改 std vector C++ 中对象的值

c++ - 具有 std::enable_if 和具体类型的模板类特化

c++ - 模板成员函数参数推导