0

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
  • @Michael Chourdakis Any reference? And why this code snippet does not compile? Commented Mar 10, 2022 at 5:30

1 Answer 1

7

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); 
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.