malloc是否创建该类的新实例? [英] Does malloc create a new instance of the class or not?

查看:63
本文介绍了malloc是否创建该类的新实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果malloc不创建新对象而是仅分配原始内存,为什么我能够通过指向该内存的指针访问类成员?

If malloc does not create a new object but only allocates raw memory, why am I able to access the class members via the pointer to this memory?

#include <iostream>
using namespace std;

const float PI = 3.141592654;

class Circle{
    float radius;
public:
    Circle(){
        cout << "Constructor called";
    }
    ~Circle(){
        cout << "Destructor called";
    }
    void Radius(){
        cout << "Enter radius: ";
        cin >> radius;
    }
    float Area(){
        return PI * radius * radius;
    }
    void Display(){
        cout << "The circle with radius " << radius
            << " units has area = " << this->Area() << " unit" << "\xFD\n";
    }
};

int main(){
    Circle *mCircle = (Circle *)malloc(sizeof(Circle));
    mCircle->Radius();
    mCircle->Display();
    return 0;
}

任何人都可以引用此消息的来源:在C ++中,规则规定在调用构造函数之前不会创建对象.

Can anyone cite a source to this: In C++ the rules state that an object isn't created until the constructor is called.

推荐答案

编译器会将对成员函数的调用转换为对静态函数的调用,其中隐含的 this 参数指向目的.这意味着对象的内容(有效或无效)与是否进行调用无关.

The compiler will translate a call to a member function into a call to a static function, with an implied this parameter pointing to the object. That means the contents of the object, valid or invalid, are not relevant to the whether the call is made.

如果方法是虚拟的,则此方法会更改,因为vtable指针必须有效.构造函数将初始化vtable指针. malloc 调用构造函数,它甚至不知道构造函数是什么-它是C留下的重物.

This changes if the method is virtual, since the vtable pointer must be valid. The constructor will initialize the vtable pointer. malloc does not call the constructor, it doesn't even know what a constructor is - it's leftover baggage from C.

请注意,这不是标准指定的 ,而是通常的实现方式.

Note that this is not specified by the standard, but is how things are typically implemented.

这篇关于malloc是否创建该类的新实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆