如何返回std :: auto_ptr [英] How to do with returning std::auto_ptr
问题描述
我有一个返回类型为auto_ptr的函数,我不知道如果用户输入了无效的参数我应该返回什么.
I have a function of which return type is an auto_ptr, i have no idea what i should return if user input an invalid parameter.
auto_ptr< myclass >& myFunction(int value)
{
switch(value)
{
case 1:
return myClassObject1; // type of myClassObject1 is auto_ptr< myclass >
case 2:
return myClassObject2; // type of myClassObject2 is auto_ptr< myclass >
default:
break;
}
// What should it return here?
}
我想这样使用它:
I''d like to use it like this:
auto_pty< myclass >& myObj = myFunction(value);
if (myObj.get() == NULL)
{
// Do something
}
所以,我的问题是,当输入值= 3时,myFunction的返回值应该是什么.
顺便说一句,MyClass是一个抽象基类.
谢谢.
So, my question is what the return value of myFunction should be when input value = 3.
BTW, MyClass is an abstract base class.
Thanks.
推荐答案
尝试
switch(...)
{
...
}
static auto_ptr default_val;
return default_val;
这将确保默认值在函数返回后仍然有效.
-提示-
我花了一段时间才知道auto_ptr
不是std::auto_ptr
...可以避免误导名称吗?
this will ensure the default value will survive the function return.
-TIP-
It tooks me a while to understand that auto_ptr
was not std::auto_ptr
... can you avoid misleading names ?
返回默认构造的auto_ptr:
Return a default constructed auto_ptr:
return std::auto_ptr<interface>();</interface>
该值应为零.
干杯,
灰
PS:如果您使用的是VC ++ 2010,请改用unique_ptr.它没有auto_ptr的一些令人惊讶的功能.
This should have a value of zero.
Cheers,
Ash
PS: If you''re using a VC++ 2010 look at using unique_ptr instead. It''s not got some of the surprising features of auto_ptr.
这篇关于如何返回std :: auto_ptr的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!