我将 auto_ptr 初始化为 NULL,稍后在游戏中我需要知道它是否为 NULL 以返回它或一个新拷贝。
我试过了
auto_ptr<RequestContext> ret = (mReqContext.get() != 0) ? mReqContext : new RequestContext();
还有其他几个类似的东西转换等等,但是 g++ 试图调用 auto_ptrs 不存在的运算符? (三元运算符)而不是使用 RequestContext* 进行三元比较。
即使我施放它也不起作用。
有什么提示吗?
编辑不相等的相等
最佳答案
我想情况类似于以下情况:
#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);
^
三元运算符要求两种结果的类型兼容,您不能让它在一种情况下返回用户定义的对象而在另一种情况下返回裸指针。注意! std::auto_ptr
在explicit 构造函数中获取一个指针,这意味着三元运算符不能将第二个参数隐式转换为std::auto_ptr
可能的解决方案:
std::auto_ptr<int> b = a.get() ? a : std::auto_ptr<int>(new int(10));
关于c++ - auto_ptr 内容的三元运算符不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1531706/