How does returning std::make_unique work?

后端 未结 5 2374
旧巷少年郎
旧巷少年郎 2021-02-19 16:05

I have a base class and its subclass:

class Base {
    public:
    virtual void hi() {
        cout << \"hi\" << endl;
    } 
};

class Derived : pub         


        
5条回答
  •  花落未央
    2021-02-19 17:01

    std::unique_ptr is not copyable, only movable. The reason you can return std::make_unique from a function declared to return std::unique_ptr is that there is a conversion from one to the other.

    So 1) is equivalent to:

    std::unique_ptr GetDerived() {
        return std::unique_ptr(std::made_unique());
    }
    

    Since the value returned from std::make_unique is an rvalue, the return value is move-constructed.

    Contrast that to 2), which is equivalent to:

    std::unique_ptr GetDerived2() { 
        std::unique_ptr a = std::make_unique(); 
        return std::unique_ptr(a); 
    }
    

    since a is an lvalue, the return value must be copy-constructed, and std::unique_ptr is non-copyable.

    3) works because you cast the lvalue a to an rvalue, and the return value can be move-constructed.

    4) and 5) work because you already have a std::unique_ptr and don't need to construct one to return.

提交回复
热议问题