-5

I am implementing a biconnected-components algorithm. There are several read-only methods written by other in the graph representation that returns a copy. How do I change these to return the actual reference instead of a copy? I am confused. Is there a good source to learn these stuff? Here are some examples:

  1. getting neighbors vertex.

    list<Vertex> Vertex::getNeighbors() const {
    return this->_neighbors;
    }
    
  2. getting edges

    vector<Edge> Graph::getEdges() const {
    unordered_set<string> distinctEdges;
    vector<Edge> edges;
    
    for (auto vertex = _verticies.begin(); vertex != _verticies.end(); vertex++) {
        auto neighbors = vertex->getNeighbors();
            for (auto neighbor = neighbors.begin(); neighbor != neighbors.end(); neighbor++) {
            Edge e(*vertex, *neighbor);
    
             if (distinctEdges.count(e.str()) > 0) {
             continue;
             }
    
        distinctEdges.insert(e.str());
        edges.push_back(e);
        }
    }
    
    return edges;
    }
    

Update: I need the reference so that I can update it later with something like this:

void Graph::updateVertex(size_t id, size_t level) {
    auto u = this->_findVertex(Vertex(id));
    if (u == this->_verticies.end()) {
       return;
    }
    u->level = level;
}

If it's a copy, it won't update the original. Thanks.

ARSN
  • 167
  • 1
  • 10

2 Answers2

1

To return read-only reference to private member of class from function, you need to change return type of function to const T&, where T is your desired type.

Now about returning reference to local variable from function. Local variables exists only while they are in scope and then they out of scope, they are destroyed. This means that returned reference to local variable would be invalid and the only way to return variable is by value.

Semyon Burov
  • 1,090
  • 1
  • 9
  • 15
  • 1
    "In scope" is a bit vague. For example, consider `void f() { int i; g(); }`. In the body of `g`, `i` is certainly not in scope, but during the evaluation of `f()`, `i` is alive even as control flows through the body of `g`. The upshot is that scope is a static property of the program, and lifetime is a dynamic property of the execution. – Kerrek SB Sep 05 '16 at 18:40
  • 1
    @KerrekSB: It's in scope; it's just not in `g`'s scope ;) – Lightness Races in Orbit Sep 05 '16 at 18:42
  • @LightnessRacesinOrbit: Yeah. Everything is in *some* scope :-) – Kerrek SB Sep 05 '16 at 18:42
0

You need to ask yourself first, why you need reference.

  1. Here for example, you should return const list<Vertex>&.

  2. Here you cannot return a reference because what you are returning is a local variable.

In both cases you gain completely nothing from returning a reference. If you think about performance or size - forget it, the compiler will optimize this and you won't see a difference.

Ethouris
  • 1,791
  • 13
  • 18