About 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.
1
2
3
4
5
6
7
8
9
10
11
12
13
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:
1
2
3
4
5
auto_pty<MyClass>& myObj = myFunction(value);
if (myObj.get() == NULL)
{
	// Do something
}


So, my question is what the return value of myFunction should be when input value = 3.

BTW, MyClass is an abstract base class.

Thanks.
Last edited on
May I suggest returning a pointer instead of a reference?
Well, that would change the semantics since auto_ptr's copy constructor transfers ownership.
The above code transfers ownership only if the result is stored in a non-reference and does
not transfer ownership otherwise. Which is, IMHO, very subtle and confusing.

OP needs to be clearer about what s/he wants to do.

Come to think of it, maybe it would be better to return a straight reference/pointer to the object. Only the scope that created the auto_ptr should know about it, ideally. Otherwise, you get hairy situations like the one you described.
1
2
3
{
    auto_pty<MyClass> myObj=myFunction(value);
}//Whoops! Someone's state is no longer consistent! 
Or perhaps a boost::shared_ptr<>
This really depends what you are doing. But I suspect you should really not be returning a reference at all.

The reason to use auto_ptr<> is so that you clean up the object when the auto_ptr<> goes out of scope. So I assume you want to control the scope of the returned auto_ptr<>. Otherwise it would make more sense to me to return a straight pointer and let something else manage the object's destruction.

If you are creating your objects in your function, then I would return an auto_ptr<> of it by copy, not by reference:

1
2
3
4
auto_ptr<MyObj> func()
{
    return auto_ptr<MyObj>(new MyObj);
}


Otherwise your object will get destroyed when the function exits.
Last edited on
Thanks all guys, for your replies.
Fortunately, i needn't to change my code at the end. I know it's not good to return a reference to auto_ptr, i think the only way to resolve it is to avoid coding like this.

On the other hand, looks like there is noway to use it in the case like this.
Topic archived. No new replies allowed.