3

我将 auto_ptr 初始化为 NULL,稍后在游戏中我需要知道它是否有 NULL 以返回它或一个新副本。

我试过这个

auto_ptr<RequestContext> ret = (mReqContext.get() != 0) ? mReqContext : new RequestContext();

还有其他几个类似的东西铸造等等,但是 g++ 试图调用 auto_ptrs 不存在的运算符?(三元运算符)而不是使用 RequestContext* 进行三元比较。

即使我施放它也不起作用。

有什么提示吗?

编辑相等为不相等

4

6 回答 6

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);
                                         ^

三元运算符对两种结果都需要兼容的类型,您不能让它在一种情况下返回用户定义的对象,而在另一种情况下返回裸指针。注意!在显式std::auto_ptr构造函数中接受一个指针,这意味着三元运算符不能将第二个参数隐式转换为std::auto_ptr

和可能的解决方案:

std::auto_ptr<int> b = a.get() ? a : std::auto_ptr<int>(new int(10));
于 2009-10-07T13:57:57.793 回答
2

mReqContext是类型auto_ptr<RequestContext>,对吧?那么问题可能是两边的类型不兼容,:因为new RequestContext()产生 a RequestContext *,但两者都必须具有公共类型才能使三元运算符可用。

可能的解决方案:要么使用

auto_ptr<RequestContext>(new RequestContext)

在 or 的右侧:使用

mReqContext.get()

在左侧:

在这两种情况下:当心指针所有权问题auto_ptr!an 中的(原始)指针auto_ptr只能由单个auto_ptr对象拥有,因此我的两个“简单”解决方案可能都不是您想要的(第一个mReqContext在非零时清除,第二个不但可能会导致mReqContext) 的重复删除。

于 2009-10-07T13:57:41.493 回答
1

尝试

auto_ptr<RequestContext> ret;
ret.reset(new stuff here);
于 2009-10-07T13:41:55.817 回答
0

你试过,把它分成两行吗?

RequestContext *p = (mReqContext.get() == 0) ? mReqContext : new RequestContext();
auto_ptr<RequestContext> ret = p;
于 2009-10-07T13:43:55.230 回答
0

您是否尝试过将所有内容都放入大括号中?

auto_ptr<RequestContext> ret =
    (mReqContext.get() == 0) ? (mReqContext) : (new RequestContext());
于 2009-10-07T13:45:14.437 回答
0

确保您没有将指针分配给 auto_ptr,这将不起作用。但是,所有这些片段都编译得很好:

#include <memory>
#include <string>

using namespace std;
int main(int argc, char * argv[] )
{
    auto_ptr<int> pX;
    pX.reset(pX.get() ? new int(1) : new int(2));
    pX = auto_ptr<int>(pX.get() ? new int(1) : new int(2));
    pX = auto_ptr<int>((pX.get()==NULL) ? new int(1) : new int(2));

    return 0;
}
于 2009-10-07T13:47:01.157 回答