Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

c++11

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

like image 470
IC_ Avatar asked Dec 05 '25 19:12

IC_


2 Answers

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.

like image 89
k.v. Avatar answered Dec 08 '25 10:12

k.v.


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

like image 26
Hatted Rooster Avatar answered Dec 08 '25 10:12

Hatted Rooster



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!