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:)
source to share
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 .
source to share
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.
source to share
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
.
source to share
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.
source to share