Difference between "Object * obj" and "Object & obj"

graph.h

struct Edge {
    int from;
    int to;
    unsigned int id;
    Edge(): from(0), to(0), id(0) {};
};

struct Vertex {
    int label;
    vector<Edge> edge;
};

class Graph: public vector<Vertex> {
    int gid;
    unsigned int edge_size;
};

class Trans {
public: 
    int tid;
    vector<Graph> graph;
};

      

vector<Trans> database;

database

- a global variable, then I call run_algo(database);

in the main function.

void run_algo(vector<Trans> &db) {
    EdgeList edges;
    for(unsigned int tid = 0; tid < db.size(); tid++) {
            Trans &t = db[tid];
            ...
       Graph g = t.graph[gid];    

      

I want to ask, what db

is an alias database

, db[tid]

is a vector of the transaction, but what if the difference between using Trans &t = db[tid];

and Trans t = db[tid];

, as the author, who writes a sample using Trans &t = db[tid];

, but I think that he should useTrans t = db[tid];

Thank:)

+3


source to share


6 answers


After

Trans &t = db[tid];

      

t is and behaves exactly like an element in db [tid], you change t, you change db [tid]



FROM

Trans t = db[tid];

      

t is just a copy of the item in db [tid], changing t will not change db [tid] here.

+2


source


Trans &t = someVar;

      

Makes a t

reference to a variable. While

Trans t = someVar;

      



Will call the copy constructor Trans

and create a completely new object.

See http://www.cprogramming.com/tutorial/references.html for details .

+2


source


 Trans t = db[tid];

      

creates a new object using the copy constructor. All changes are applied to this new object.

 Trans& t = db[tid];

      

is an alias for db[tid]

. Any changes to t

also apply to db[tid]

.

+1


source


As vector :: operator [] returns an object by reference, then using

Trans &t = db[tid];

      

will be more efficient as it will not force a copy of the object stored in the vector, unlike:

Trans t = db[tid];

      

However, in the first case, any changes to 't' will change the object stored in the vector.

+1


source


The difference between Trans &t

and Trans t

is that the first is a reference, which is basically an alias for another variable, in this case whatever is outputted from the vector. The other Trans t

, which is a new variable, where the material in the vector is copied using operator=

to copy data.

Using a link avoids copying done while using Trans t

.

0


source


Trans &t = db[tid];

      

means it t

is an alias for an object db[tid]

. alias is a different name for the object, but the left and right values ​​are equal to the left and right values db[tid]

. so if you make some changes to t

, you will have the same modification on db[tid]

.

while:

Trans t = db[tid];

      

means to t

execute on a copy of the object db[tid]

. so if you edit t

, db[tid]

will not be affected.

0


source







All Articles