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?
This is a perfectly valid C++ code and does exactly what you expect it to do:
Don't worry, you will not end up returning a reference to a local variable this way.
The code is fine, it will return an int by value with the value of i.
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