简体   繁体   中英

The 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 is a global variable, then i call run_algo(database); in 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 db is a alias to database , db[tid] is a Transaction vector, but what if the difference between using Trans &t = db[tid]; and Trans t = db[tid]; , since the author who write the sample using Trans &t = db[tid]; , but i think it should use Trans t = db[tid];

Thanks:)

Trans &t = someVar;

Is making t a reference to the variable. Whereas

Trans t = someVar;

Would invoke the copy-constructor of Trans and create a completely new object.

See http://www.cprogramming.com/tutorial/references.html for more information as well.

After

Trans &t = db[tid];

t is and behaves exactly as the item in db[tid], you change t, you change db[tid]

With

Trans t = db[tid];

t is merely a copy of the item in db[tid], changing t won't change db[tid] here.

 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 will also apply to db[tid] .

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

Trans &t = db[tid];

will be more effecient, as it does 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 being taken out of the vector. The other is Trans t which is a new variable, where the stuff in the vector is being copied by using operator= to copy the data.

Using the reference avoids the copy made when you use Trans t .

Trans &t = db[tid];

means that t is an alias of the object db[tid] . an alias is a different name for the object but the left and right values are equals to left and right values of db[tid] . so if you make some modification to t you will have same modification on db[tid] .

while :

Trans t = db[tid];

means that t is made with a copy of the object db[tid] . so if you edit t , db[tid] will not be affected.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM