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

前端 未结 5 774
猫巷女王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:52

    Because malloc doesn't call the class's constructor, and doesn't know anything about any particular alignment requirements it might have. If you need to use malloc (not recommended), take a look at placement new (assuming you don't want to overload the regular new for some reason).

提交回复
热议问题