List of all available Websheets
Viewing cpp/cs104/cpp11/raii1 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 | Assume the process function uses a "resource" to do its job. <br><br> Thus during execution the number of resources should be reduced by 1 and then restored upon completion of the <tt>process</tt> function. <br><br> The solution seems simple but what if <tt>f1</tt> throws an exception?? <br> You could put the call to f1 in a <tt>try</tt> block and then add <tt>catch</tt> a catch block to restore the value, and then rethrow. <strong>But there is a better way. See exercise <tt>raii2</tt> for a solution to this problem.</strong> |
Remarks Comments, history, license, etc. | Copied from problem cpp/cs104/cpp11/sharedptr1 (author: redekopp@usc.edu) |
Engine | |
Template / Reference solution |
using namespace std; int numResources = 2; 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 \[ REDACTED ]\ cout << "in useResourceToProcess(): numResources = " << numResources << endl; // Do the work \[ REDACTED \show: f1(a); ]\ // restore the number of resources \[ REDACTED ]\ } 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'.