代码之家  ›  专栏  ›  技术社区  ›  Arkaitz Jimenez

自动ptr内容上的三元运算符不工作

  •  3
  • Arkaitz Jimenez  · 技术社区  · 16 年前

    我试过这个

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

    还有其他一些类似的东西,但是g++试图调用auto_ptrs nonexistent操作符(三值运算符)而不是使用RequestContext*进行三值比较。

    即使我投下它也不起作用。

    有什么提示吗?

    编辑了“相等”为“不相等”

    6 回复  |  直到 16 年前
        1
  •  20
  •   UncleBens    16 年前

    #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);
    }
    

    这是科莫非常有启发性的错误信息:

    "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<int> b = a.get() ? a : std::auto_ptr<int>(new int(10));
    
        2
  •  2
  •   hjhill    16 年前

    mReqContext 是一种 auto_ptr<RequestContext> 对吧??那么问题可能是服务器两侧的类型不兼容 : new RequestContext() 产生 RequestContext *

    auto_ptr<RequestContext>(new RequestContext)
    

    在右边的 或使用

    mReqContext.get()
    

    : .

    在这两种情况下:都要小心指针所有权问题 auto_ptr ! 中的(原始)指针 自动检查 只能归一个人所有 自动检查 对象,所以我的两个“简单”解决方案可能不是您想要的(第一个解决方案清除) 如果该值不为零,则第二个值不为零,但可能导致重复删除 mReqContext ).

        3
  •  1
  •   alexkr    16 年前

    尝试

    auto_ptr<RequestContext> ret;
    ret.reset(new stuff here);
    
        4
  •  0
  •   RED SOFT ADAIR    16 年前

    RequestContext *p = (mReqContext.get() == 0) ? mReqContext : new RequestContext();
    auto_ptr<RequestContext> ret = p;
    
        5
  •  0
  •   foraidt    16 年前

    auto_ptr<RequestContext> ret =
        (mReqContext.get() == 0) ? (mReqContext) : (new RequestContext());
    
        6
  •  0
  •   alexkr    16 年前

    确保您没有将指针分配给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;
    }