Effective C + + clauses 15, 16 provide access to the original resource in the Resource management Class | | Paired use new and delete to take the same form

Source: Internet
Author: User

1. Provide access to the original resource in the resource management class

The first few articles are great, they are a bulwark against resource leaks, but many APIs point directly to resources, and at this point we need direct access to the original resources.

Here, there are two ways to solve the above problem, we can convert the Raii object to the original resource. Through explicit conversions and implicit conversions.

Typically, TR1:: shared_ptr and auto_ptr all provide a GET member function that performs an explicit conversion, which returns the copy of the original pointer inside the smart pointer. Because it also overloads the pointer-value operator *–>. Of course, it can also be implicitly converted to the bottom primitive pointer.

Class font

{

Fonthandle get () const

{

return F;

}//fonthandle is a resource, an explicit conversion function

operator Fonthandle () const

{

return F;

}//implicit conversions may cause "unintentional type conversions"

}

The choice between the two methods depends on the specific work that the RAII class is designed for.

Remember:

APIs often require access to raw resources, so each RAII needs to provide a way to get the resources it manages.

Access to raw resources can be explicitly converted and implicitly converted, generally explicit conversions are more secure, but implicit conversions are more convenient for customers.

2. Use new and delete in pairs

Remember:

New array, call delete[] + array name directly.

That is: if you use [] in the new expression, you must also use [] in the corresponding expression, and if you do not use [] in the new expression, do not use [] in the corresponding delete expression.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.