Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

About return const reference in C++

Tags:

c++

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.

like image 964
Roger Luo Avatar asked Dec 28 '22 04:12

Roger Luo


1 Answers

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

  • Returning const reference to local variable from a function
like image 171
Mark Byers Avatar answered Jan 08 '23 05:01

Mark Byers