Home > Back-end >  Misunderstanding with move constructor
Misunderstanding with move constructor

Time:02-19

I have such class, where I create a move constructor

class Test
{
private:
    int m_a;

public:
    Test(int val) { m_a = val; }

    Test (const Test &) {}
    
    // move constructor
    Test (Test && d)
    {
        std::cout << &m_a << std::endl;   // Line X
        std::cout << &d.m_a << std::endl;
    }

    void print()
    {
        std::cout << m_a << std::endl;
    }
};

I also create a function to test move constructor

void fun(Test a)
{ return ; }

Than in main function I create 2 objects of class above and call function to test move constructor

int main()
{
    Test a {50};
    Test b {100};

    fun(a);
    fun(std::move(a));

    fun(b);
    fun(std::move(b));

    return 0;
}

When I looked at the output, I was surprised, because the address of o m_a variable in line X has same address for both objects.

0x7ffc40d37bb4   // look at this
0x7ffc40d37bac
0x7ffc40d37bb4   // look at this
0x7ffc40d37bb0

How is it possible ? It's not static member, what is going on ? Compiler optimization or what ?

CodePudding user response:

Each time fun(Test a) is invoked, an instance of Test is created on the stack. Each time fun() returns, the stack frame is freed.

So when invoked twice in a row, the chance is great that you get an instance of Test created at exact same location on the stack.

If you wanted to take Test by reference, it should be void fun(Test&& a).

CodePudding user response:

How is it possible ?

The parameters of the separate invocations of fun don't have overlapping storage lifetimes. Hence, they can use the same storage.

  • Related