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

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

    section [basic.life] of the standard says

    The lifetime of an object is a runtime property of the object. An object is said to have non-trivial initialization if it is of a class or aggregate type and it or one of its members is initialized by a constructor other than a trivial default constructor. [ Note: initialization by a trivial copy/move constructor is non-trivial initialization. — end note ] The lifetime of an object of type T begins when:

    • storage with the proper alignment and size for type T is obtained, and
    • if the object has non-trivial initialization, its initialization is complete.

    Since your class has virtual members, it requires non-trivial initialization. You can't assign an object whose lifetime hasn't started, you have to initialize it with new.

提交回复
热议问题