从RAII对象泄漏资源 [英] Leaking resource from a RAII object

查看:154
本文介绍了从RAII对象泄漏资源的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读Scott Meyers的Effective C ++,现在我在第15项,提供对资源管理类中原始资源的访问。这里是一个例子:

I'm reading Scott Meyers' Effective C++ and now I'm at the Item 15, providing access to raw resource in resource-managing classes. Here is an example:

class Font { // RAII class
public:
    explicit Font(FontHandle fh) // acquire resource;
        : f(fh) // use pass-by-value, because the
    {} // C API does
    ~Font() { releaseFont(f ); } // release resource
    ... // handle copying (see Item14)
private:
    FontHandle f; // the raw font resource
};

他建议引入一个显式的转换成员函数来访问原始资源:

He proposed to introduce an explicit conversion member function for getting access to the raw resource:

class Font {
public:
    ...
    FontHandle get() const { return f; } // explicit conversion function
    ...
};

这里是他说的:


有些程序员可能会发现需要明确请求这样的
转换,足以避免使用该类。那么,在
中, 会增加泄露字体的机会 ,这是
Font类设计用来防止的东西。

Some programmers might find the need to explicitly request such conversions off-putting enough to avoid using the class. That, in turn, would increase the chances of leaking fonts, the very thing the Font class is designed to prevent.

我不明白如何提供原始资源的访问权限增加了泄漏字体的机会?我们刚刚返回了一个指向资源对象的原始指针的副本。我们不必担心访问使用 get 成员函数获取的dangle指针,因为delete操作符只有在超出范围时才会被调用。

I didn't understand how the providing acces to the raw-resource increase the chances of leaking fonts? We just returned a copy of the raw pointer to the resource object. And we shouldn't worry about accessing to a dangle pointer acquired with the get member function, becuase the delete operator will be call only if we go out of scope.

我错过了什么?

推荐答案

想想,如果你能访问资源没有什么阻止你做任何你想要的资源。你可以复制它,摧毁它,重新创建它或任何。所有没有使用防止资源泄漏的类。
如果您重新创建它或复制它,您可以访问非托管资源,增加泄露的风险。
如果你销毁它,你可能会在你的代码

Think about it, if you can get access to the resource nothing stop you from doing whatever you want with the resource. You may copy it, destroy it, recreate it or whatever. All without using the class which prevent you from resource leak. If you recreate it, or copy it you have an access to an unmanaged resource increasing the risk of leak. And if you destroy it, you may create a big mess in your code

这篇关于从RAII对象泄漏资源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆