Are there any valid use cases to use new and delete, raw pointers or c-style arrays with modern C++?

前端 未结 19 932
梦谈多话
梦谈多话 2020-11-22 07:20

Here\'s a notable video (Stop teaching C) about that paradigm change to take in teaching the c++ language.

And an also notable blog post

19条回答
  •  一生所求
    2020-11-22 07:52

    The primary use case where I still use raw pointers is when implementing a hierarchy that uses covariant return types.

    For example:

    #include 
    #include 
    
    class Base
    {
    public:
        virtual ~Base() {}
    
        virtual Base* clone() const = 0;
    };
    
    class Foo : public Base
    {
    public:
        ~Foo() override {}
    
        // Case A in main wouldn't work if this returned `Base*`
        Foo* clone() const override { return new Foo(); }
    };
    
    class Bar : public Base
    {
    public:
        ~Bar() override {}
    
        // Case A in main wouldn't work if this returned `Base*`
        Bar* clone() const override { return new Bar(); }
    };
    
    int main()
    {
        Foo defaultFoo;
        Bar defaultBar;
    
        // Case A: Can maintain the same type when cloning
        std::unique_ptr fooCopy(defaultFoo.clone());
        std::unique_ptr barCopy(defaultBar.clone());
    
        // Case B: Of course cloning to a base type still works
        std::unique_ptr base1(fooCopy->clone());
        std::unique_ptr base2(barCopy->clone());
    
        return 0;
    }
    

提交回复
热议问题