Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

method result declared by value, implementation by reference valid?

Tags:

c++

I have been wondering if it is valid c++ if I return something from a method by reference, while the method is actually declared to return by value:

class A {
public:
    int method(){
        int i = 123;
        int& iref = i;
        return iref;
    }
};

This compiles fine and seems to work. From what I understand this should return by value, as declared in the method's signature. I do not want to end up returning a reference to the local variable. Does anyone know if this is 'proper c++ code' without traps?

like image 892
wolpers Avatar asked Dec 26 '22 20:12

wolpers


2 Answers

This is a perfectly valid C++ code and does exactly what you expect it to do:

  • Have a local variable
  • Have a local reference to that local variable
  • Make a copy of the variable referenced to by your local reference
  • Return that copy to a caller (unwind stack, destroying both local variable and a reference to it)

Don't worry, you will not end up returning a reference to a local variable this way.

like image 170
YePhIcK Avatar answered Feb 13 '23 09:02

YePhIcK


The code is fine, it will return an int by value with the value of i.

like image 33
juanchopanza Avatar answered Feb 13 '23 11:02

juanchopanza