C++ new[] into base class pointer crash on array access

前端 未结 5 737
南笙
南笙 2020-12-21 10:24

When I allocate a single object, this code works fine. When I try to add array syntax, it segfaults. Why is this? My goal here is to hide from the outside world the fact

5条回答
  •  攒了一身酷
    2020-12-21 11:05

    I have figured out a workaround based on your answers. It allows me to hide the implementation specifics using a layer of indirection. It also allows me to mix and match objects in my array. Thanks!

    #include 
    
    using namespace std;
    
    // file 1
    
    class a
    {
        public:
            virtual void m() { }
            virtual ~a() { }
    };
    
    // file 2
    
    class b : public a
    {
        int x;
    
        public:
            void m() { cout << "b!\n"; }
    };
    
    // file 3
    
    class c : public a
    {
        a **s;
    
        public:
            // PROBLEMATIC SECTION
            c() { s = new a* [10]; for(int i = 0; i < 10; i++) s[i] = new b(); }
            void m() { for(int i = 0; i < 10; i++) s[i]->m(); }
            ~c() { for(int i = 0; i < 10; i++) delete s[i]; delete[] s; }
            // END PROBLEMATIC SECTION
    };
    
    // file 4
    
    int main(void)
    {
        c o;
    
        o.m();
    
        return 0;
    }
    

提交回复
热议问题