How does returning std::make_unique work?

后端 未结 5 2348
旧巷少年郎
旧巷少年郎 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 16:59

    std::unique_ptr<> has no copy constructor, but it does have a move constructor from a related pointer, i.e.

    unique_ptr( unique_ptr&& u );         // move ctor
    template< class U, class E >
    unique_ptr( unique_ptr&& u );   // move ctor from related unique_ptr
    

    The second constructor requires certain conditions (see here). So why did your code 2 not work, but 4 did? In 4, you didn't use any constructor, since the return type was identical to the object, the object itself was returned. In 2 on the other hand, the return type was different and a constructor call was needed, but that required std::move().

提交回复
热议问题