Why can I not call my class's constructor from an instance of that class in C++?

前端 未结 10 1525
情深已故
情深已故 2021-01-03 16:39

When can an object of a class call the destructor of that class, as if it\'s a regular function? Why can\'t it call the constructor of the same class, as one of its regular

10条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-03 17:01

    If you really need to do something like this, just create an additional function and call it from outside AND from the constructor itself, but let's see what happens when you do need such a call:

    #include
    
    class A
    {
    //members
    };
    
    int main()
    {
    //allocate buffer
    char* buffer = new char[sizeof(A)];
    //construct A on that memory space
    A * ptrToA = ::new (buffer) A();
    //destroy the object
    ptrToA->~A();
    //deallocate the buffer
    delete[] buffer;
    }
    

    One instance where you can find placement new usage is the standard containers. The allocator takes in the responsibility to allocate the buffer (allocate member) and the objects are constructed over that buffer as they are added into the container. For example, when you do reserve on vector object, it reserves the space for N objects meaning allocates space for N objects but does not construct them. Then when you do push_back etc, to add elements, they are created over that buffer. Basically, it is a technique to reduce the overhead of repeated calls to memory allocation function. And then when done, the vector destructor would destroy the objects calling the destructor explicitly for all objects in it and then call the deallocate() function of the allocator to release the memory. Hope this helps.

提交回复
热议问题