Best practices - returning pointer from a function

时间:2016-04-21 22:22:13

标签: c++ pointers c++11

I just have a dilemma, how should I return smart pointer from a function, when function might fail. I could pick one of the following options:

  1. Return pointer, and throw exception if function fails:

    std::shared_ptr foo() {
        // ...
        if (!ok)
          throw;
        return ptr;
    }

  1. Return pointer, and return empty pointer, if function fails

    std::shared_ptr foo() {
        // ...
        if (!ok)
            return std::shared_ptr();

        return ptr;
    }

  1. Pass pointer by reference, and return bool flag

    bool foo(std::shared_ptr& ptr) {
        // ...
        if (ok)
            ptr = ...;

        return ok;
    }

Is there any best practice, guideline, how to report, that function didn't execute properly? Or is it usually project-specific?

Thanks for your answers

2 个答案:

答案 0 :(得分:1)

Honestly the correct answer depends on what the called function does, and what the consequence of the failure is. For libraries I'd suggest either throwing an exception or returning a value that indicates failure. Passing the pointer by reference and returning a flag seems questionable unless you're using that idiom frequently, or if there is a reason to externally manage the shared pointer.

答案 1 :(得分:-1)

Good question. I think it depends on the occurrence or nature of the error. If you foresee this error to happen semi-occasionally or it's an expected error, or even it's an error that can be recovered somehow then I would use method 2 or 3.

However, if the error is something that shouldn't normally happen and it would cause the application to not function properly I would use the 1st method.

My reasoning for this is that exceptions could possibly be slower compared to the other two methods (see Are Exceptions in C++ really slow, and by nature exceptions flow up to the main caller so it natural that you want a critical error to move up and stop the process.