I initialize an auto_ptr to NULL and later in the game I need to know if it has NULL or not to return it or a new copy.
I've tried this
auto_ptr<RequestContext> ret = (mReqContext.get() != 0) ? mReqContext : new RequestContext();
And several other similar stuff casting and so, but g++ tries to invoke auto_ptrs nonexistent operator? (the ternary operator) instead of using RequestContext* for the ternary comparison.
Even if I cast it it doesn't work.
Any hint?
Edited the equal for non-equal
I suppose the situation is analogous to the following:
#include <iostream>
#include <memory>
int main()
{
std::auto_ptr<int> a(new int(10));
std::auto_ptr<int> b = a.get() ? a : new int(10);
}
And here's Comeau's very enlightening error message:
"ComeauTest.c", line 7: error: operand types are incompatible ("std::auto_ptr<int>"
and "int *")
std::auto_ptr<int> b = a.get() ? a : new int(10);
^
Ternary operator requires compatible types for both results, you can't have it return user-defined object in one case and a naked pointer in the other. NB! std::auto_ptr
takes a pointer in an explicit constructor, which means the ternary operator cannot implicitly convert the second argument to std::auto_ptr
And possible solution:
std::auto_ptr<int> b = a.get() ? a : std::auto_ptr<int>(new int(10));