Consider the following code:

#include <iostream>
using namespace std;

class someClass
{
public:
    someClass(){ cout<<"someClass"<<endl; }
    void g() const { cout<<"g()"<<endl;}
};

int main()
{
    void* memory = new void*[5*(sizeof(someClass)/sizeof(char))];
    someClass *someClassArray = reinterpret_cast<someClass*>(memory);

    for(int i=0;i<5;i++)
    {
        someClassArray[i].g();
    }       
}

The output for this code is:

g()
g()
g()
g()
g()

Which means that no constructor was called. But in array someClassArray are onjects of someClass type and I am allowed to call a g() function and get a proper output.

Why this program is executet correctly, while no object of type someClass is consructed?

有帮助吗?

解决方案

When member function g() is called the compiler simply pass to it as the first argument the pointer to the object (that is to an element of the allocated array of type void * that you interpret as someClass *). The function does not use this pointer to access any data member of the class. In fact for this simple class there is nothing that the constructor has to construct. The class has no data members. So there is no problem to call the function.

其他提示

someClass is a class with no state. It is not surprising that g() is not handled like a vtable pointer, but rather a regular function.

What you are doing here is undefined behaviour pandering to intuition, reinterpret_cast, rather than specs.

Memory allocation has been done for the someClass objects, with you call of new. However, as the call is new void and not new someClass, it hasn't called someClass constructor.

The call of g() works because this pointer has been allocated. Only constructor operations will never be executed.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top