简体   繁体   中英

Question about returning an unique_ptr from a function

As per the document , which says that

We already have implicit moves for local values and function parameters in a return statement. The following code compiles just fine:

 std::unique_ptr<T> f(std::unique_ptr<T> ptr) { return ptr; }

However, the following code does not compile

std::unique_ptr<T> f(std::unique_ptr<T> && ptr) { return ptr; }

Instead, you must type

std::unique_ptr<T> f(std::unique_ptr<T> && ptr) { return std::move(ptr); }

Here are my questions:

1.There is no copy ctor for std::unique_ptr<T> indeed, there should not a function could accept a parameter declared as std::unique_ptr<T> . See this code snippet , it does not compile.

#include <memory>

class FooImage{};

std::unique_ptr<FooImage> FoolFunc(std::unique_ptr<FooImage> foo)
{
    return foo;
}

int main()
{

    std::unique_ptr<FooImage> uniq_ptr(new FooImage);

    FoolFunc(uniq_ptr);
}

2.why

std::unique_ptr<T> f(std::unique_ptr<T> && ptr) {
    return ptr;
} 

does not compile?

Could somebody shed some light on this matter?

1.There is no copy ctor for std::unique_ptr<T> indeed, there should not a function could accept a parameter declared as std::unique_ptr<T> .

In fact, this is ok as long as you move the original std::unique_ptr to this local parameter

FoolFunc(std::move(uniq_ptr)); // ok
FoolFunc(std::unique_ptr<FooImage>{new FooImage}); // also ok

2.why

std::unique_ptr<T> f(std::unique_ptr<T> && ptr) { return ptr; }

does not compile?

Although the type of ptr is an rvalue reference, it is itself an lvalue , so return ptr will call the copy ctor, you need to use std::move to cast ptr to an rvalue again

std::unique_ptr<T> f(std::unique_ptr<T> && ptr) { 
    return std::move(ptr); 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM