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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…