简体   繁体   English

C ++,何时应返回引用?

[英]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: 在Main函数中,我有STL排序:

**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. 出现了问题,如果使用vector <Node *> getChildren(),则代码将出现严重的多余问题,仅使用vector <Node *>&getChildren()可以。 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. 当不返回引用时, getChildren将在每次调用该vector时返回该vector的新副本。

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 . 第一次调用getChildren返回的副本与第二次调用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. 这意味着begin()end()在不同的向量上,因此您将永远无法从一个迭代到另一个。

When you return a reference, both call return a reference to the same vector, so you can iterate from begin() to end() 当您返回引用时,两个调用都返回对相同向量的引用,因此您可以从begin()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. 要补充@TheDark所说的内容(对我来说,它并不清楚):该引用返回作为类一部分的实际向量。 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): 如果要在本地对向量进行排序而不在类中对向量进行排序,则需要执行以下操作(由@TheDark提供的原因,为此您可以返回引用或副本):

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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