In C++, why is `new` needed to dynamically create an object rather just allocation?

前端 未结 5 773
猫巷女王i
猫巷女王i 2021-01-18 08:30

I\'ve got this trivial class hierarchy:

class Base {
public:
    virtual int x( ) const = 0;
};

class Derived : public Base {
    int _x;
public:
    Derive         


        
5条回答
  •  无人共我
    2021-01-18 08:56

    Let's go down the line

    1. why is my application crashing, if I don't use new?

    Virtual table is corrupted.

    The virtual table is stuck right after the allocated memory. when you new a class, the generated code will properly set up the vtable. However, malloc will not properly initialize the vtable

    To see the virtual table, run g++ -fdump-class-hierarchy

    Vtable for Derived
    Derived::_ZTV7Derived: 3u entries
    0     (int (*)(...))0
    8     (int (*)(...))(& _ZTI7Derived)
    16    Derived::x
    
    Class Derived
       size=16 align=8
       base size=12 base align=8
    Derived (0x10209fc40) 0
        vptr=((& Derived::_ZTV7Derived) + 16u) <-- notice how this is part of the structure
      Base (0x10209fcb0) 0 nearly-empty
          primary-for Derived (0x10209fc40)
    

    For a similar reason, without overloading operator=, the generated assembly code will only copy the data and not the vtable [again, the compiler only knows to copy the data, not the vtable]

    If you want to see a pointer-based version with a valid vtable function:

    Derived e(123);
    d = &e;
    
    1. Would I need to use new also for non-polymorphic types?

    If you are using virtual functions, then yes, even for non-polymorphic types

    1. I hope that the alignment needed for my class is the class size as returned by sizeof, so that any address in the form address_returned_by_malloc + i * sizeof(my_class) is suitable to allocate my objects.

    Alignment is not an issue.

提交回复
热议问题