How does returning std::make_unique work?

后端 未结 5 2372
旧巷少年郎
旧巷少年郎 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:55

    In every case but (2) the returned value was treated as (some kind of) rvalue. In (2) it was not, because the types did not match the implicit move was blocked.

    In a later iteration of the standard, (2) would also implicitly move.

    All of them shortly engage in undefined behaviour after being called, as they try to delete a Derived object via pointer-to-Base. To fix this, record a deleter function.

    template
    using smart_unique=std::unique_ptr;
    
    template
    smart_unique make_smart_unique( Args&&... args ){
      return {
        new T(std::forward(args)...),
        [](void*ptr){ delete static_cast(ptr); }
      };
    }
    template
    static const smart_unique empty_smart_unique{ nullptr, [](void*){} };
    

    These are unique pointers smart enough to handle polymorphism like shared_ptr can.

提交回复
热议问题