简体   繁体   中英

C++, when should return reference?

class Node{   
private:    
vector<Node*> children;    

public:     
vector< Node* > getChildren ();    
//or    
vector< Node* >& getChildren();
}    

In the Main function somewhere i have STL sort:

**stl::sort((n->getChildren()).begin(),(n->getChildren()).end(),comp);**

here comes the problem, if using vector< Node* > getChildren() the code will have bad excess problem, only using vector< Node* >& getChildren() works. I am confused, why only reference works in this case?

When you are not returning a reference, getChildren will return a new copy of the vector each time it is called.

This means that in this line:

stl::sort((n->getChildren()).begin(),(n->getChildren()).end(),comp);

The first call to getChildren returns a different copy than the second call to getChildren . This then means that the begin() and end() are on different vectors, so you will never be able to iterate from one to the other.

When you return a reference, both call return a reference to the same vector, so you can iterate from begin() to end()

To add to what @TheDark said (for me it is not stated clearly): The reference returns the actual vector that is part of the class. Thus if you make modifications to the vector, the modifications are made on the vector in the class and other functions and the class will see the changes.

If you return a copy, the changes are made to the copy only and the class and other functions will not see the changes.

If you want to sort the vector locally and not sort the vector in the class, you need to do the following (reason provided by @TheDark, for this you can return either a reference or copy):

vector< Node* > localVector = n->getChildren();
stl::sort(localVector.begin(), localVector.end(), comp);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM