这个C ++代码会发生什么?

时间:2014-08-30 08:53:26

标签: c++

在以下代码中:

    class Object
    {
    public:
        int a, b, c;
        Object() 
        {
            cout << "Creating an object.." << endl;
        }
        ~Object()
        {
            cout << "Deleting an object.." << endl;
        }
    };

    int main(int argc, char *[]) 
    {
        Object *obj = &(Object()); // Why is the destructor called here?
        obj->a = 2; // After the destruction, why didn't this cause an access violation?
        cout << obj->a; // Prints 2.
        getchar();
        return 0;
    }

输出是:

Creating an object..
Deleting an object..
2

在上面的代码中, 为什么在行Object *obj = &(Object());中调用析构函数?可能是因为Object()返回临时对象。如果是这样,为什么下一行不会导致访问冲突,因为obj的值是已删除的临时对象的地址?

0 个答案:

没有答案