Leaking resource from a RAII object

2019-09-07 21:06发布

问题:

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
    ...
};

Here is what he said:

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.

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.

What did I miss?

回答1:

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