Consequences of using ampersand before function name in C ++?

For example:

inline string &GetLabel( ) { return m_Label; }; 

Where m_Label is a member variable of a private class.

As I think, I understand that, this function will return a reference to the m_Label variable. What would be the consequences of using this throughout my program, and would it be better to just return the value instead of the link? Thanks!

+7
source share
5 answers

It returns a link to a private member.

There are many cases where this is desirable, but care must be taken.

An IMO is generally not recommended to return a copy of an internal object that is not an integral type for general performance reasons. Yes, I know, premature optimization is not very good, but actually it is not optimization, it is just good performance practice that allows the caller to determine the consequences of performance; if he wants a copy, he may simply not declare the variable that he assigns to it as a reference.

There are two general rules that I use here:

1) If you do not want the caller to be able to directly modify the private object, declare the return value as a reference to a constant:

 inline const string& GetLabel() const{ return m_Label; } 

2) The caller should not store the link returned by the class method, it should be used only locally, where the parent is guaranteed to be in scope.

If for some reason you need callers to be able to store a link to your internal objects, use smart pointers instead.

+6
source

Ampersand is not before the function name just like after the return type. it returns a link to string .

The consequence of this is that the caller of this function could change the value of m_label via a link. On the other hand, it avoids copying the string. You may need the link and function to be const , for example:

 inline const string& GetLabel() const { return m_Label; } 

The best of both worlds. You avoid copying, but callers cannot modify your object.

+11
source

Returning the link means that the calling code can change the value of your member variable after returning. This is very dangerous, unless you intend to do it.

Better reference const or return by value (without & ).

+2
source

One of the consequences is that if the object-object is destroyed, the link becomes invalid:

 Object* o = new Object; string& label = o->GetLabel(); delete o; // label becomes a dangling reference here. 

Another meaning is that the caller can modify the string. You can fix this by returning a link to a constant.

+2
source

You're right. This is a link to a string member.

The implication is that if the caller had to assign a value or otherwise change the returned string, then they would also change the member variable. If this is not the intention, you may want to return a copy by value to avoid encapsulation violation.

+1
source

All Articles