auto_ptr 内容上的三元运算符不起作用
我将 auto_ptr 初始化为 NULL,稍后在游戏中我需要知道它是否为 NULL,是否返回它或一个新副本。
我已经尝试过这个
auto_ptr<RequestContext> ret = (mReqContext.get() != 0) ? mReqContext : new RequestContext();
以及其他几个类似的东西铸造等等,但是 g++ 尝试调用 auto_ptrs 不存在的运算符? (三元运算符)而不是使用 RequestContext* 进行三元比较。
即使我投了它也不起作用。
有什么提示吗?
将等于编辑为不等于
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
我想情况类似于以下内容:
这是 Comeau 非常有启发性的错误消息:
三元运算符需要两种结果兼容的类型,你不能让它在一种情况下返回用户定义的对象,在另一种情况下返回裸指针。注意!
std::auto_ptr
在显式构造函数中获取指针,这意味着三元运算符无法将第二个参数隐式转换为std::auto_ptr
并且可能的解决方案:
I suppose the situation is analogous to the following:
And here's Comeau's very enlightening error message:
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 tostd::auto_ptr
And possible solution:
mReqContext
的类型是auto_ptr
,对吗?那么问题可能是:
两边的类型不兼容,因为new RequestContext()
产生一个RequestContext *
,但两者必须有一个共同的使三元运算符可用的类型。使用
可能的解决方案:要么在
:
的右侧,要么在
:
的左侧使用。在这两种情况下:请注意
auto_ptr
的指针所有权问题!auto_ptr
中的(原始)指针只能由单个auto_ptr
对象拥有,因此我的两个“简单”解决方案可能都不是您想要的(第一个)第一个在mReqContext
非零时清除,第二个不清除,但可能导致mReqContext
的重复删除)。mReqContext
is of typeauto_ptr<RequestContext>
, right? Then the problem may be incompatible types on both sides of the:
becausenew RequestContext()
yields aRequestContext *
, but both must have a common type for the ternary operator to be usable.Possible solutions: Either use
at the right side of the
:
or useat the left side of the
:
.In both cases: Beware of the pointer ownership issues with
auto_ptr
! The (raw) pointer in anauto_ptr
can be only be owned by a singleauto_ptr
object, so both of my "simple" solutions may not be what you want (the first one clears outmReqContext
when it is non-zero, the second one doesn't but may lead to duplicate deletion ofmReqContext
).尝试
try
您是否尝试过将其分成两行?
Did you try, breaking that up into two lines?
您是否尝试过将其全部放入大括号中?
Have you tried putting it all into braces?
确保您没有将指针分配给 auto_ptr,这将不起作用。
然而,所有这些片段都编译得很好:
Make sure you are not assigning pointer to the auto_ptr, this will not work.
However, all these fragments compiling just fine: