Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Misunderstanding with move constructor

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 ?

>Solution :

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).

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading