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


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 {
    int tid;
    vector<Graph> graph;


vector<Trans> 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];



source to share

6 answers


Trans &t = db[tid];


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


Trans t = db[tid];


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



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 .



 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]




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.



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




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]



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.



All Articles