Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
613 views
in Technique[技术] by (71.8m points)

c++ - If in malloc object is not created then why does this code works?

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
";
    }
    ~Test()
    {
        cout << "Test : dtor
";
    }
    void Hello()
    {
        cout << "Test : Hello World
";
    }
};

int main()
{

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

    return 0;
}


OUTPUT:
Hello World
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.

blatantly stolen from Columbo and LRIO:

[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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...