【问题标题】:C++, when should return reference?C++,什么时候应该返回引用?
【发布时间】:2015-12-01 05:46:02
【问题描述】:
class Node{   
private:    
vector<Node*> children;    

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

在 Main 函数的某处我有 STL 排序:

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

问题来了,如果使用vector getChildren() 代码会有严重的过度问题,只有使用vector& getChildren() 有效。 我很困惑,为什么在这种情况下只有参考有效?

【问题讨论】:

  • 这个问题看起来和我今天看到的另一个问题很相似:stackoverflow.com/q/34008337/1553090
  • 即使这没有造成问题,它仍然毫无意义。为什么sort一个向量然后扔掉排序好的向量?
  • 你的意思是std::sort 吗?

标签: c++ sorting vector stl


【解决方案1】:

当您不返回引用时,getChildren 将在每次调用时返回 vector 的新副本。

这意味着在这一行:

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

getChildren 的第一次调用与对getChildren 的第二次调用返回的副本不同。这意味着 begin()end() 位于不同的向量上,因此您将永远无法从一个迭代到另一个。

当你返回一个引用时,两个调用都返回一个对同一个向量的引用,所以你可以从begin()迭代到end()

【讨论】:

  • 确保添加返回const 引用的函数的const 版本。 vector&lt; Node* &gt; const&amp; getChildren() const;.
【解决方案2】:

补充@TheDark 所说的内容(对我来说没有明确说明): 引用返回作为类的一部分的实际向量。因此,如果您对向量进行修改,则会在类和其他函数中对向量进行修改,并且类将看到更改。

如果您返回副本,则仅对副本进行更改,类和其他函数将看不到更改。

如果要在本地对向量进行排序而不是在类中对向量进行排序,则需要执行以下操作(原因由@TheDark 提供,为此您可以返回引用或副本):

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

【讨论】:

    猜你喜欢
    • 2017-06-06
    • 2020-07-16
    • 2019-07-08
    • 1970-01-01
    • 1970-01-01
    • 2011-03-19
    • 1970-01-01
    • 2010-10-18
    • 1970-01-01
    相关资源
    最近更新 更多