Can unique_ptr return local objects successfully?

unique_ptr < int > test () {

      unique_ptr<int> ppp(new  int(10));
      return   ppp;

}

As shown in the

code above, ppp can successfully return no error. Ppp is a left value, so it must not be moved, so you have to execute the copy constructor, but unique_ptr does not have a copy construction.
who can give me a big explanation?

Mar.02,2021

As shown in the
code above, ppp can successfully return no error. Ppp is a left value, so it must not be moved, so you have to execute the copy constructor, but unique_ptr does not have a copy construction.

your judgment is wrong. Let me give you an example as follows:

-sharpinclude <iostream>
-sharpinclude <memory>

using namespace std;
static unique_ptr<int> p1 = std::make_unique<int>(10);

// move -> copy construction -> failed
unique_ptr<int> foo()
{
    auto p = make_unique<int>(10);
    return p;                   // 1 ok p is local parameter(rvalue) can run it with move
    //return move( p );         // 2 also ok
    //return p1;                // NOK. p1 is lvalue can not performance move on it.
}

int main()
{
    unique_ptr<int> p = foo();

    cout << *p << endl;
    return 0;
}

first of all, ppp is the local value returned by return, which is the right value rather than the left value;
second, std::unique_ptr does not accept the left value as the copy constructor of the input parameter. Only this:

unique_ptr( unique_ptr&& u ) noexcept;

think about this example again:
idelines-zh-CN/blob/master/CppCoreGuidelines-zh-CN.md-sharp%E7%A4%BA%E4%BE%8B-103" rel=" nofollow noreferrer "> https://github.com/lynnboy/Cp.

Menu