include <iostream> voidsomeFunction() { Resource *ptr = new Resource; int x; std::cout << "Enter an integer: "; std::cin >> x;
if (x == 0) return; // the function returns early, and ptr won’t be deleted! // do stuff with ptr here delete ptr; }
case2: 抛出异常
1 2 3 4 5 6 7 8 9 10 11 12 13 14
#include<iostream> voidsomeFunction() { Resource *ptr = new Resource; int x; std::cout << "Enter an integer: "; std::cin >> x; if (x == 0) throw0; // the function returns early, and ptr won’t be deleted! // do stuff with ptr here delete ptr; }
#include<iostream> template<classT> classAuto_ptr1 { T* m_ptr; public: // Pass in a pointer to "own" via the constructor Auto_ptr1(T* ptr=nullptr) :m_ptr(ptr) { } // The destructor will make sure it gets deallocated ~Auto_ptr1() { delete m_ptr; } // Overload dereference and operator-> so we can use Auto_ptr1 like m_ptr. T& operator*() const { return *m_ptr; } T* operator->() const { return m_ptr; } }; // A sample class to prove the above works classResource { public: Resource() { std::cout << "Resource acquired\n"; } ~Resource() { std::cout << "Resource destroyed\n"; } }; intmain() { Auto_ptr1<Resource> res(new Resource()); // Note the allocation of memory here // ... but no explicit delete needed // Also note that the Resource in angled braces doesn't need a * symbol, since that's supplied by the template return0; } // res goes out of scope here, and destroys the allocated Resource for us
#include<iostream> template<classT> classAuto_ptr1 { T* m_ptr; public: // Pass in a pointer to "own" via the constructor Auto_ptr1(T* ptr=nullptr) :m_ptr(ptr) { } // The destructor will make sure it gets deallocated ~Auto_ptr1() { delete m_ptr; } // Overload dereference and operator-> so we can use Auto_ptr1 like m_ptr. T& operator*() const { return *m_ptr; } T* operator->() const { return m_ptr; } }; // A sample class to prove the above works classResource { public: Resource() { std::cout << "Resource acquired\n"; } ~Resource() { std::cout << "Resource destroyed\n"; } voidsayHi(){ std::cout << "Hi!\n"; } }; voidsomeFunction() { Auto_ptr1<Resource> ptr(new Resource()); // ptr now owns the Resource int x; std::cout << "Enter an integer: "; std::cin >> x; if (x == 0) return; // the function returns early // do stuff with ptr here ptr->sayHi(); } intmain() { someFunction(); return0; }