mercredi 9 mars 2022

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?

Aucun commentaire:

Enregistrer un commentaire