如果在malloc对象没有创建然后为什么这段代码工作? [英] If in malloc object is not created then why does this code works?

查看:102
本文介绍了如果在malloc对象没有创建然后为什么这段代码工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我们对c ++中的类使用malloc / free时,不会创建对象。那么为什么这段代码工作?
如果没有创建对象,那么它不能给出下面提到的输出。

An object is not created when we use malloc/free for a class in c++. Then why does this code works? If an object is not created then it must not give the output mentioned below.

class Test
{
public:
    Test()
    {
        cout << "Test : ctor\r\n";
    }
    ~Test()
    {
        cout << "Test : dtor\r\n";
    }
    void Hello()
    {
        cout << "Test : Hello World\r\n";
    }
};

int main()
{

    cout << "2\n";
    Test* t2 = (Test*) malloc(sizeof Test);
    t2->Hello();
    free(t2);

    return 0;
}


OUTPUT:
Hello World


推荐答案

未定义行为是简短的答案。长的答案是,因为你的类没有虚拟方法直接调用它只是一个隐式的这个参数指向你分配的内存的函数调用。如果你的任何方法访问它会导致更多未定义的行为,因为对象尚未构造。

Undefined Behavior is the short answer. The long answer is that because your class has no virtual methods calling them directly is just a function call with an implicit this parameter that points to the memory you've allocated. That said if any of your methods were to access this it would cause more undefined behavior because the object hasn't been constructed.

从Columbo和LRIO公开偷窃:

blatantly stolen from Columbo and LRIO:


11:3.8 / 1]:对象的生命周期是对象的运行时属性。如果对象是类或聚合类型并且它或其成员之一由除了琐碎的默认构造函数之外的构造函数初始化,则该对象被称为具有非平凡初始化。 [注意:通过一个简单的复制/移动构造函数的初始化是非平凡的初始化。 -end note]

[C++11: 3.8/1]: 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 critical bit there is the it the pointer to the object can contain data other than just a place where the members are stored. It is up to the implementation to decide what that is.

这篇关于如果在malloc对象没有创建然后为什么这段代码工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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