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
c ++


source to share


No one has answered this question yet

See similar questions:

951
Can a local memory variable be accessed outside of its scope?

or similar:

8499
What is the "->" operator in C ++?
4247
The definitive C ++ guide and book list
3076
What are the differences between a pointer variable and a reference variable in C ++?
2387
What does an explicit keyword mean?
1994
What are the basic rules and idioms for operator overloading?
1911
What is the rule of three?
1783
C ++ 11 introduced a standardized memory model. What does it mean? And how will this affect C ++ programming?
1717
What is the copy and swap idiom?
1709
How can I profile C ++ code running on Linux?
1475
What is the effect of extern "C" in C ++?



All Articles
Loading...
X
Show
Funny
Dev
Pics