Ask about when to call the c++ move constructor. I think it's the time of the call, but the move constructor is not created :(

Asked 2 years ago, Updated 2 years ago, 26 views

The writing code is as follows:

#include <iostream>

using namespace std;

class CMyData
{
public:
    CMyData(int Param):m_nData(Param)
    {
        cout << "CMyData(int)" << endl;
    }

    CMyData(const CMyData &rhs): m_nData(rhs.m_nData)
    {
        cout << "CMyData( const CMyData & ) " << endl;
    }

    CMyData(const CMyData &&rhs) : m_nData(rhs.m_nData)
    {
        cout << "CMyData(const CMyData && ) " << endl;
    }

    ~CMyData()
    {
       cout << "~CMyData()" << endl;
    }

    operator int() { return m_nData; }


    CMyData operator+(const CMyData & rhs)
    {
        CMyData result(0);

        result.m_nData = this->m_nData + rhs.m_nData;

        return result;
    }

    CMyData& operator=( const CMyData & rhs)
    {
        m_nData = rhs.m_nData;

        return *this;
    }

private:
    int m_nData = 0;

};

int main(void)
{
    cout << "***Begin***" << endl;

    CMyData a(0), b(3), c(4);

    a = b + c; /// at this point.

    cout << a << endl;

    cout << "*** end *** " << endl;

    return 0;
}

After b+c operation, it seems that a moving generator should be created in the process of substituting it with a, but it cannot be created. Why is that?

c++

2022-09-22 21:32

1 Answers

When a=b+c and assign the result of b+c is a, I think the Copy Constructor is the question for to call why not?

Similar questions were then asked in #1931 and #2227. Please refer to it.

In summary, the return value of one function is related to optimization for assign to another variable.


2022-09-22 21:32

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.