简体   繁体   中英

"this" pointer in parameterized constructor points to another address than from outside

I have the following code:

#include <iostream>

class Entity {

public:
    int x;
    int y;

    Entity() {
        std::cout << "Default contructor: " << this << std::endl;
    }

    Entity(int x, int y) {
        this->x = x;
        this->y = y;

        std::cout << "Constructor with parameter: " << this << std::endl;
    }
};

int main()
{
    Entity e;
    e = Entity(10, 20);

    std::cout << "Adress from outside: " << &e << std::endl;

    std::cin.get();

    return 0;
}

Why is the address in the main fuction the same as the address in the default constructor? And is there any way to get access to the memory address of the object initialized with parameters from main ?

Why is the address in the main fuction the same as the address in the default constructor?

Because e is the same object, always. You cannot move it in memory or anything like that. It will occupy the same memory spot until it dies.
What you are using in e = Entity(10, 20);is called move assignment operator . Note that despite the name, nothing is actually moved, because it cannot do that. Default compiler generated move assignment operator simply calls move assignment on each of the class members (and move assignment for ints is equivalent to a copy).

And is there any way to get access to the memory address of the object initialized with parameters from main?

No. That object was a temporary and it is gone after the semicolon finishing this line. You would need to give it a name to keep it as another variable.

Why is the address in the main fuction the same as the address in the default constructor?

Because the object in the main function was initialised using the default constructor.

“this” pointer in parameterized constructor points to another address than from outside

This is because the paramtetrised constructor was used to initialise a different object. Namely, it was used to initialise the temporary object that was used to assign the value of the object in main. Since those two objects have overlapping lifetimes and are not sub objects of one another, they must have a distinct address.

And is there any way to get access to the memory address of the object initialized with parameters from main?

The lifetime of the temporary object ends at the full expression (at the semicolon in this case) where it is in (unless it is extended by binding to a reference with longer lifetime, which doesn't apply here) . Thus, you cannot use it afterwards. You could use a variable instead of a temporary which would allow you to access it:

Entity e;
Entity e2(10, 20);
e = e2;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM