What's going on in this C ++ code?

In the following code:

    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;
    }

      

Output:

Creating an object..
Deleting an object..
2

      

In the above code, why is the destructor called in a string Object *obj = &(Object());

? This could be because it is Object()

returning a temporary object. If so, why didn't the next line cause an access violation because the value obj

is the address of a remote temporary object?

+3


source to share





All Articles