Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

c++11 - 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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...