Roger Luo
Roger Luo

Reputation: 355

About return const reference in 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.

Upvotes: 4

Views: 979

Answers (3)

shihongzhi
shihongzhi

Reputation: 1931

const A& operator * (const A & rhs) const
{
    return A(this->m_num1 * rhs.m_num1, this->m_num2*rhs.m_num1);
}

this function you return a reference to a local variable. Local variable will destroyed when return from this funcutin operator* . So it is dangerous. You can just return A, but not A&.When return A, function will copy a temp A for return.

Upvotes: 1

111111
111111

Reputation: 16148

 const A& operator * (const A & rhs) const
 {
     return A(this->m_num1 * rhs.m_num1, this->m_num2*rhs.m_num1);
 }

This is bad here.

You are returning a dangling reference, if it works it is coincidence.

You are returning something that exists in a stack frame which has been destroyed. Just return by value to fix it.

Upvotes: 1

Mark Byers
Mark Byers

Reputation: 838086

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

Upvotes: 8

Related Questions