This code:
int& methodTwo() { return x; }
means that the function returns a reference to an integer. In the same way as when passing a value by reference to a function, if the return value of methodTwo , the value returned by methodTwo returned. In this case, a field of class x .
In the code you wrote, this means that you allow the private variable x to hide its scope (class field) and be transmitted in the outside world. This, of course, is bad practice (because x can be changed in ways that may violate the foo class, but it is certainly valid.
Remember public / private / protected - this is only compilation time . When your application compiles, private fields are located next to public fields, and there is no protection against modification. The same is true for managed languages ββsuch as C # and Java.
As a rule, you avoid returning links because it makes it crazy - it is difficult to understand when constructors / destructors are called. However, returning the link may be faster. If your method returned a structure type that was HUGE, then returning a const reference to the same structure type should only take four to eight-bytes (a pointer to this object). However, there are better optimization methods for this kind of thing.
Chris smith
source share