About returning const reference in C ++

I am confused about returning a const reference in C ++. Therefore, I write the code block below and test on gnu C ++ and visual studio. And find another answer. Can anyone tell an advantage using the return const link in C ++, and the reason causes a different behavior in the 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; } 

In Gnu C ++, he reported the correct answer. But the visual training compiler failed.

+4
source share
3 answers

This returns a reference to a local variable that is not resolved:

 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 link and undefined behavior.

Similar

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

It’s bad here.

You return a dangling link, if it works, this is a coincidence.

You are returning what exists in the frame of the stack that was destroyed. Just return the value to fix it.

+1
source
 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 link to a local variable. The local variable will be destroyed when it returns from this funcutin operator* . So this is dangerous. You can simply return A , but not A& . When returning A function will copy temp A to return.

+1
source

Source: https://habr.com/ru/post/1401180/


All Articles