Search code examples
c++raii

Best way to use RAII conditionally


I have a nice resource managing class. For concreteness, lets have it be a File class for managing a FILE* (handling the open and close operations)

What is the usual approach when there are cases where the resource doesn't need to be managed by me, and is someone else's responsibility?

For ilustrative purposes, I currently have something like this:

int main(int argc, char** argv)
{
    File my_file(argv[1]); //I unconditionaly obtain the resource
    //...
    return 0;  //and unconditionally relinquish with the destructor
}

And want something like

int main()
{
    if(argc <= 1){
        //use stdin that is already available
    }else{
        //obtain a file from argv[1]
    }
    //...
    if(argc <= 1){
        //nothing to do
    }else{
        //close the file we obtained
    }
}

(but less ugly, more robust, etc...)


Solution

  • Your RAII class is already keeping enough state to know when to destroy the resource it is controlling. It can also contain a flag that tells it if the resource should be destroyed, or you can use a special value on the counter to indicate that the resource is controlled outside the class.

    Then all you need is a way to control the state when you obtain the resource. You can have two different constructors for example, or a parameter on the constructor with a default value. You could have an Attach method that attaches an existing resource. It's entirely up to you.