IC_
IC_

Reputation: 1789

C++. How to return null pointer instead of function return type?

I have a function that checks regex and returning std::vector<int> according to regex result. I need to check if function fail/success. On success return vector object, on fail nullptr to later check if (somefunc() == nullptr) // do smth

Upvotes: 2

Views: 2467

Answers (3)

Remy Lebeau
Remy Lebeau

Reputation: 595732

There are many different options:

  • return a std::vector<int>* pointer, optionally wrapped in std::unique_ptr for lifetime management. Return nullptr on failure.

  • pass the std::vector by a reference parameter, and then return a bool for success/failure.

  • throw an exception on failure.

  • return a std::pair<std::vector<int>, bool>, where the pair's second field indicates success/failure.

Upvotes: 0

k.v.
k.v.

Reputation: 1223

Value of return type std::vector<int> cannot be nullptr.

The most straightforward way in this case is to return std::unique_ptr<std::vector<int>> instead - in this case it's possible to return nullptr.

Other options:

  • throw an exception in case of fail
  • use optional<std::vector<int>> as return type (either boost::optional or std::optional if your compiler has this C++17 feature)
  • return bool parameter and have std::vector<int>& as output parameter of function

The best way to go really depends on the use case. For example, if result vector of size 0 is equivalent to 'fail' - feel free to use this kind of knowledge in your code and just check if return vector is empty to know whether function failed or succeed.

In my practice I almost always stick to return optional (boost or std, depending on environment restriction). Such interface is the most clear way to state the fact that 'result can either be present or not'.

To sum up - this is not a problem with the only one right solution. Possible options are listed above - and it's only a matter of your personal experience and environmental restrictions/convetions - which option to choose.

Upvotes: 11

Hatted Rooster
Hatted Rooster

Reputation: 36463

You could return a std::unique_ptr<std::vector<int>> and check that value, or throw an exception, or check vector.size() == 0 etc.

Upvotes: 1

Related Questions