c++ - auto_ptr 内容的三元运算符不起作用

标签 c++ stl auto-ptr

我将 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_ptrexplicit 构造函数中获取一个指针,这意味着三元运算符不能将第二个参数隐式转换为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/

相关文章:

c++ - C++中是否有用于 "linear quadratic regulator"函数的库

visual-studio-2008 - VC2008中的自动指针构造函数

c++ - map 删除困难

c++ - 是否存在将 long 转换为指针有效的情况

c++ - C++标准算法中的ForwardIterator和OutputIterator能一样吗?

c++ - 迭代 std::map 的顺序是否已知(并由标准保证)?

c++ - auto_ptr 和容器 - C++

c++ - C++ 中的自动指针 (auto_ptr)

c++ - cmake/make (OBJECT) 依赖性问题—— header 更改时不重建

c++ - 如何按索引存储 vector 的 vector