I am confused about returning the const reference in C++. So i write below code block and test on gnu c++ and visual studio. And find different answer. Could anyone tell the benefit using return const reference in C++ and the reason cause different behavior on differnt compiler.
#include <iostream>
using namespace std;
class A
{
public:
    A(int num1, int num2):m_num1(num1), m_num2(num2)
    {
            cout<<"A::A"<<endl;
    }
    const A& operator * (const A & rhs) const
    {
            return A(this->m_num1 * rhs.m_num1, this->m_num2*rhs.m_num1);
    }
    A(const A& rhs)
{
            this->m_num1 = rhs.m_num1;
            this->m_num2 = rhs.m_num2;
            cout<<"A::A(A&)"<<endl;
    }
    const A& operator = (const A& rhs)
    {
            cout<<"A::Operator="<<endl;
            return *this;
    }
    void Display();
private:
    int m_num1;
    int m_num2;
};
void A::Display()
{
    cout<<"num1:"<<m_num1<<" num2:"<<m_num2<<endl;
}
int main()
{
    A a1(2,3), a2(3,4);
    A a3 = a1 * a2;
    a3.Display();
    return 0;
}
On Gnu C++, it did report the correct answer. But failed on visual studion compiler.
This is returning a reference to a local variable, which is not allowed:
const A& operator * (const A & rhs) const
{
    return A(this->m_num1 * rhs.m_num1, this->m_num2*rhs.m_num1);
}
You have a dangling reference and undefined behaviour.
Related
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With