Search code examples
c++referencetry-catchshared-ptr

How to avoid shared pointers in C++ caused by try/catch?


I use shared pointers because of variable can only live in block where it was created.

int main(void) {

    std::shared_ptr<project::log::Log> log;

    try {
        log = make_shared<annmu::log::Log>("error.log"); // can throw eception
    }
    catch(std::exception &e) {
        std::cout << "Error\n\n";
        return 0;
    }

}

I would like to avoid shared pointers and created code more simple. Something like following code (not working code).

int main(void) {

    project::log::Log log; // can throw eception

    try {
        log = project::log::Log("error.log"); // can throw eception
    }
    catch(std::exception &e) {
        std::cout << "Error\n\n";
        return 0;
    }

}

Is it good way to avoid shared pointers? Is it more efficient solution? In second solution the object is created two times.

Thank you for you answer.


Solution

  • It is always good practice to avoid using shared pointers, unless you are actually sharing the pointer. You could use a unique_ptr as a drop in replacement.
    It is not a bad idea to have a non-throwing constructor, which constructs the object into a valid-empty state. Handling exceptions in construction is always more complex than handling an exception during an operation. Complex solutions require more brain-power, and brain-power is a scarce resource in large programs
    So in general, I think everything you say is right. I like to think of objects as having 6 distinct stages.

    • Allocation
    • Construction
    • Initialisation
    • Active // Do useful functions, etc
    • Destruction
    • Deallocation

    For simple objects reducing this to just construction/destruction is just convenient, and reduces how much you have to think about. For heavy-weight objects it makes sense to separate out each stage and make them separately testable. You get better error handling and error reporting this way (IMHO)