List of all available Websheets
Viewing cpp/cs104/cpp11/raii2 by redekopp@usc.edu. You have unsaved changes. Log in above to create, edit, preview and publish Websheets.
Property | Value |
---|---|
Description html markup shown to student | Recall that all local variables are deallocated at the end of their enclosing <tt>{...}</tt> braces. The compiler will ensure their destructor is called as the object goes out of scope. <br><br> We can take advantage of this by making a dummy object where we "acquisition" in the constructor (i.e. at initialization) and then write code in the destructor to "give back" the resources we acquired. <br><br> In this way whether we exit the scope normally or due to an exception the compiler will ensure the destructor is called and we can use that opportunity to give back our resource. <br><br> This idiom of declaring a scoped object where the constructor performs some task and the destructor undoes/cleansup is a common idea in C++ and is known as <strong> Resources Acquisition Is/In Initialization (RAII) </strong>. <br><br> Complete the constructor and destructor of the <tt>Checkout</tt> class below. |
Remarks Comments, history, license, etc. | Copied from problem cpp/cs104/cpp11/raii1 (author: redekopp@usc.edu) Copied from problem cpp/cs104/cpp11/sharedptr1 (author: redekopp@usc.edu) |
Engine | |
Template / Reference solution |
using namespace std; int numResources = 2; struct Checkout { int& numR; Checkout(int& numRes) : numR(numRes) { \[ REDACTED ]\ } ~Checkout() { \[ REDACTED ]\ } }; void f1(int x) { // Perform some processing but may throw an exception \hide[ if(x > 0) throw invalid_argument("bad"); else if(x < 0) throw logic_error("really bad"); else cout << "Normal" << endl; ]\ } // Should decrement numResources during execution void process(int a) { // Assume that to process, this function "uses" a resources // Thus it should decrement the number of resources // and then restore it back at the end of the function Checkout c(numResources); cout << "in useResourceToProcess(): numResources = " << numResources << endl; // Do the work f1(a); // restore the number of resources } int main() { try { int a; cin >> a; process(a); } catch(exception& e){ cout << "Exception: " << e.what() << endl; } cout << "back in main(): numResources = " << numResources << endl; return 0; } |
C++ test suite json list of stdin/args tests e.g. [{"stdin":"hi", "args":["4", "5"]}, {"stdin":"noargs"}] to just run once with no input use [{}] | [{"stdin":"0"},{"stdin":"1"},{"stdin":"-1"}] |
Is example? i.e., just a demo | |
Add compiler flag(s) json list of flags e.g. ["-Wno-unused-variable"] | ["-std=c++11"] |
Note: problems are open-source by default (see 'Public permissions'). Assumed license for open problems is Creative Commons 4.0 Attribution-ShareAlike unless specified in 'Remarks'.