The ternary operator on auto_ptr does not work

I initialize auto_ptr to NULL, and later in the game I need to know if it is NULL or not returning it or a new copy.

I tried this

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

And a few other similar castings, etc., but is g ++ trying to call the nonexistent auto_ptrs operator? (ternary operator) instead of using RequestContext * for triple comparisons.

Even if I leave him, he does not work.

Any clues?

Edited peer to peer

+3
source share
6 answers

I believe the situation is similar to the following:

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

And here is Como's very enlightening error message:

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

, . NB! std::auto_ptr , , std::auto_ptr

:

std::auto_ptr<int> b = a.get() ? a : std::auto_ptr<int>(new int(10));
+20

mReqContext auto_ptr<RequestContext>, ? :, new RequestContext() a RequestContext *, .

:

auto_ptr<RequestContext>(new RequestContext)

:

mReqContext.get()

:.

: auto_ptr! (raw) auto_ptr auto_ptr, "" , ( mReqContext, -zero, - , mReqContext).

+2

to try

auto_ptr<RequestContext> ret;
ret.reset(new stuff here);
+1
source

Have you tried breaking this into two lines?

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

Have you tried putting all this in braces?

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

Make sure you do not assign a pointer to auto_ptr, this will not work. However, all of these fragments compile just fine:

#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;
}
0
source

Source: https://habr.com/ru/post/1719512/


All Articles