如何返回引用或副本
How to return reference or copy
我有以下代码:
EdgeSet Graph::GetNodeOutcomingEdges(long long NodeId) {
//NodeEdgeMap is an unordereded_map
NodeEdgeMap::iterator it = NodeOutcomingEdges.find(NodeId);
if (it != NodeOutcomingEdges.end()) {
return *(*(it)).second;
}
return EdgeSet();
}
然后. .
EdgeSet& OutcomingEdges = RoadGraph.GetNodeOutcomingEdges(Expandee.GetId());
因为值不一定在映射中,所以我必须以某种方式解释它,在理想情况下,返回一个空的(新)EdgeSet。我可以抛出异常,但有必要吗?这在VS下可以很好地编译(可能已经解释了RVO),但在g++中就不是这样了。
EdgeSet& Graph::GetNodeOutcomingEdges(long long NodeId) {
//NodeEdgeMap is an unordereded_map
NodeEdgeMap::iterator it = NodeOutcomingEdges.find(NodeId);
if (it != NodeOutcomingEdges.end()) {
return *(*(it)).second;
}
static EdgeSet emptySet;
return emptySet;
}
这只是一种可能的方法:在您的Graph类中,定义EdgeSet类型的空成员变量,并使用一些将其标识为空的属性,例如"mEmptyFlag"布尔值:
class Graph {
...
static EdgeSet mEmptyNode(params defining empty node here);
...
}
EdgeSet Graph::GetNodeOutcomingEdges(long long NodeId) {
//NodeEdgeMap is an unordereded_map
NodeEdgeMap::iterator it = NodeOutcomingEdges.find(NodeId);
if (it != NodeOutcomingEdges.end()) {
return *(*(it)).second;
}
return Graph::mEmptyNode;
}
callerFunct {
EdgeSet& OutcomingEdges = RoadGraph.GetNodeOutcomingEdges(Expandee.GetId());
if (OutcomingEdges.mEmptyflag==true) {
deal with empty node here
} else {
....
}
}
或者更好的封装,隐藏mEmptyFlag并为EdgeSet提供"IsEmpty()"函数。
假设您实际上想要返回一个引用,以允许调用者修改返回的对象,您可以返回一个指向已找到对象的指针,或者如果未找到则返回一个空指针:
EdgeSet* Graph::GetNodeOutcomingEdges(long long NodeId) {
//NodeEdgeMap is an unordereded_map
NodeEdgeMap::iterator it = NodeOutcomingEdges.find(NodeId);
if (it != NodeOutcomingEdges.end()) {
return it->second;
}
return 0;
}
或者,返回一个可以为空的boost::optional<EdgeSet&>
。
但是你不应该"仅仅因为"返回一个引用,如果你希望调用者能够引用存储在映射中的相同对象,并且能够修改它,你应该返回一个引用。否则,返回一个副本或const引用会更好。
NodeEdgeMap::iterator Graph::GetNodeOutcomingEdges(long long NodeId) {
return NodeOutcomingEdges.find(NodeId);
}
相关文章:
- 使用unique_ptr并返回引用,或者我应该使用shared_ptr并在需要时制作副本
- C ++引用函数参数似乎包含原始对象的副本,而不是充当"real reference"
- 为什么基于范围的 for 循环中的结构化绑定只是一个副本而不是引用?
- 标准库容器结构是否存储副本或引用?
- 如何声明接受转发引用并返回引用或副本的函数模板
- 如何在我的源代码中找到所有发生的情况,其中std :: string被传递给方法作为副本而不是恒定引用
- 取消引用指针以创建数组的副本
- 返回不带副本 ctor 的引用
- 为什么在C 11中推荐的值(如果需要副本),如果const引用也只花费单个副本,则建议通过值(如果需要副本)
- 如何通过制作副本从函数返回引用
- 可以在同一函数中引用副本本地变量是否可以
- 为什么从三元文字中绑定到const引用副本
- 传递常量引用与创建临时常量副本相同,那么为什么要传递常量引用
- 为什么在 constexpr 函数中允许返回对常量指针的引用,但不返回副本
- 初始化引用时何时以及为何获得副本
- 处理对“vector_binary_operation”类中“表达式”的引用,而无需不必要的副本
- 按方法返回副本或引用
- 您能否从抽象引用创建具体对象的副本
- 常量引用和创建副本
- 使复制的成员引用变量引用副本的成员,而不是原始成员的成员