我将auto_ptr初始化为NULL,稍后在游戏中我需要知道它是否为NULL以返回它或新副本.
我试过这个
auto_ptr<RequestContext> ret = (mReqContext.get() != 0) ? mReqContext : new RequestContext();
和其他几个类似的东西一样,但是g ++试图调用auto_ptrs不存在的运算符?(三元运算符)而不是使用RequestContext*进行三元比较.
即使我施展它也行不通.
任何提示?
编辑等于不平等
Unc*_*ens 20
我想情况类似于以下情况:
#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);
}
这是Comeau非常有启发性的错误信息:
"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);
                                         ^
三元运算符需要两个结果的兼容类型,您不能让它在一个案例中返回用户定义的对象而在另一个案例中返回裸指针.NB!std::auto_ptr在显式构造函数中获取指针,这意味着三元运算符不能隐式地将第二个参数转换为std::auto_ptr
可能的解决方案:
std::auto_ptr<int> b = a.get() ? a : std::auto_ptr<int>(new int(10));