3. Resource Management (Terms: 13-17)

Source: Internet
Author: User

Clause 13: manage resources by object.

A.Resource leakage:

#include <iostream>using namespace std;struct INT {int v;INT(int x) : v(x) { cout << "INT constructor called." << endl; }~INT() { cout << "INT deconstructor called." << endl; }};int main() {INT *tmp = new INT(6);cout << (*tmp).v << endl;cout << tmp->v << endl;}

(No destructor is called, and resources are not released in the heap)

B.Use objects to manage resources:

Template <typename T> class resource_ptr/* adds the management type resource_ptr */{public: resource_ptr (T * P = NULL): r_ptr (p) {cout <"resource_ptr constructor called; "<Endl ;}~ Resource_ptr () {cout <"resource_ptr deconstructor called;" <Endl; If (r_ptr) delete r_ptr;} const T & operator * () const {return * r_ptr ;} T & operator * () {return * r_ptr;} const T * operator-> () const {return r_ptr;} t * operator-> () {return r_ptr ;} /* T * Get () {return r_ptr;} */PRIVATE: T * r_ptr;}; typedef resource_ptr <int> r_ptr; int main () {/* int * TMP = new int (6); */r_ptr TMP = r_ptr (New int (6); cout <(* TMP ). v <Endl; cout <TMP-> v <Endl ;}

(Use an object to call the destructor to release resources through delete)

 

3. Resource Management (Terms: 13-17)

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.