Home > Software design >  Question about returning an unique_ptr from a function
Question about returning an unique_ptr from a function

Time:03-10

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?

CodePudding user response:

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); 
}
  • Related