Method result declared by value, implementation by reference valid?

I was wondering if this is really 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 and seems to work. From what I understand, this should be returned by value, as stated in the method signature. I do not want to return a link to a local variable. Does anyone know if this is the "correct C ++ code" without traps?

+4
source share
2 answers

This is perfectly valid C ++ code and does exactly what you expect from it:

  • Enter a local variable
  • Enter a local link to this local variable
  • Make a copy of the variable referenced by your local link
  • Return this copy to the caller (untwist the stack, destroy both the local variable and the link to it)

Do not worry, you will not return the link to the local variable in this way.

+6
source

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

+4
source

All Articles