Article 15: Provide access to the original resource in the resource management classprovide access to raw resources in resources-managing classes
The Resource management class (Resource-managing classes) is great. They are a bulwark against resource leaks. In a good environment, you will rely on such classes to handle all interactions with resources. Instead of dealing directly with primitive resources, the environment is not perfect, Many APIs directly involve resources, so sometimes you can only bypass the resource management object to access the raw resources directly.
For example, clause 13 imports an idea that uses a smart pointer such as AUTO_PTR or tr1::shared_ptr to save the factory function, such as a createinvestment call result:
Suppose you want to handle a investment object with a function like this:
int daysheld (const investment* PI);
If you call it this way:
int days = Daysheld (PINV);
But not compile, because daysheld need is a investment* pointer, but to it is a type of tr1::shared_ptr<investment> object.
A function is required to convert the Raii class object (in this case, tr1::shared_ptr) to the original resource it contains (this example is the investment* at the bottom). There are two ways to achieve the goal: explicit and implicit conversions.
Both Tr1::shared_ptr and Auto_ptr provide a GET member function to perform an explicit conversion, which returns a copy of the original pointer inside the smart pointer:
int days = Daysheld (Pinv.get ());
Just like (almost) all smart pointers, Tr1::shared_ptr and auto_ptr also overload the pointer-value operators (operator-> and operator*), which allow implicit conversion to the bottom raw pointer.
Attention:
APIs often require access to raw resources, so each RAII class should provide a way to "get the resources it manages".
Access to the original resource may be explicitly converted or implicitly converted. In general, explicit conversions are more secure, but implicit conversions are compared to customers.
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Effective c++--Clause 15 (chapter 3rd)