C++ vs Java constructors

前端 未结 14 2480
一个人的身影
一个人的身影 2021-02-09 20:31

According to John C. Mitchell - Concepts in programming languages,

[...] Java guarantees that a constructor is called whenever an object is created.

14条回答
  •  悲哀的现实
    2021-02-09 21:25

    even in the case we use statically allocated memory buffer for object creation , constructor is called.

    can be seen in the following code snippet. i haven't seen any general case yet where constructor is not called, but then there is so much to be seen :)

    include

    using namespace std;

    class Object

    {

    public:

    Object();

    ~Object();

    };

    inline Object::Object()

    {

    cout << "Constructor\n";

    };

    inline Object::~Object()

    {

    cout << "Destructor\n";

    };

    int main()

    {

    char buffer[2 * sizeof(Object)];

    Object *obj = new(buffer) Object; // placement new, 1st object

    new(buffer + sizeof(Object)) Object; // placement new, 2nd object

    // delete obj; // DON’T DO THIS

    obj[0].~Object(); // destroy 1st object

    obj[1].~Object(); // destroy 2nd object

    }

提交回复
热议问题