[英]What should I return in a member function if a condition is not met?
For example: 例如:
class Foo{
int data;
// ...
}
And there is a member function: 并且有一个成员函数:
Foo func(int a){
if(a > 10) return Foo(a);
else {} // problem is here, I do not want return
any Foo object, do I throw exception? how?
}
So, I do not want to return a new empty Foo
object in else block, how can I handle this situation in an idiomatic way? 因此,我不想在else块中返回一个新的空
Foo
对象,如何以惯用的方式处理这种情况?
Yes, if you've found that there's some scenario in which your function should suddenly not be returning a value, then either: 是的,如果您发现在某些情况下您的函数应该突然不返回值,则可以:
If the pre-condition is absolutely needed for the function to continue, then throwing an exception is the proper way of handling it. 如果继续运行该函数绝对需要先决条件,则抛出异常是处理它的正确方法。 If the condition isn't required explicitly throughout the rest of the function, then you have a couple options:
如果在其余函数中没有明确要求该条件,则有两种选择:
std::unique_ptr
. std::unique_ptr
。 I don't recommend this approach because it has unnecessary dynamic memory allocation. boost::optional<Foo>
or in a future TS std::experimental::optional<Foo>
. boost::optional<Foo>
或将来的TS std::experimental::optional<Foo>
。 This expresses intent that the value may or may not be there. your best bet is to return a pointer: 最好的选择是返回一个指针:
Foo* func(int a){
if(a > 10) return new Foo(a);
else return 0; // else return plain zerro
}
C++11 C ++ 11
Foo* func(int a){
if(a > 10) return new Foo(a);
else return nullptr;
}
of course you'll need to check if returned object does exist in your calling function: 当然,您需要检查调用的函数中是否确实存在返回的对象:
Foo* ptr = func(5);
if(ptr)
{
// use ptr
*ptr;
}
else
{
// do not use it
}
// and delete it
if(ptr) delete ptr;
// in c++11 version no need to check just:
delete ptr;
sorry I didn't see you do not want to return 0... 抱歉,我没有看到您不想返回0 ...
Foo* func(int a){
if(a > 10) return new Foo(a);
else throw(a);
}
try
{
Foo* get = func(4); // this will throw
}
catch(int)
{
//handle the error here
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.