nick
nick

Reputation: 872

pass parameter with pointer or with reference when the origin data is pointer?

I need to read some data from binary file, which i save the data pointer in a vector.

I want to handle them with best performance.

I have two design, please see this:

struct A {
  int a, b,c;
}
void Handle(const A & a) {
// do something
}

void Handle(A * a) {

}
std::vector<A* > av; // this is read from file
for (int i = 0; i < 1000; ++i) {
  // is there any difference between these two method? !!!!
  // Handle(av[i]);
  // Handle(*(av[i]))  // does this create a temp variable which speed down the code?
}

I want to know is there any difference between them? and which is faster?

Upvotes: 1

Views: 64

Answers (1)

anatolyg
anatolyg

Reputation: 28251

Pointer and reference are mostly the same when regarding performance: their implementation in the runnable code is the same (or course, there are exceptions to this rule, but I cannot think of any).

The difference between reference and pointer is mostly for the programmer - reference has cleaner syntax (that is, you don't need to dereference it when using data), while pointers support nullptr value and pointer arithmetic. The general style rule is to "use references when you can, and pointers when you must".

It is also possible to convert from pointer to reference and back, so these choices are equally powerful when writing code. For example:

void Handle(A& a)
{
    std::cout << a.field;
    another_function_which_receives_reference(a);
    another_function_which_receives_pointer(&a);
}

void Handle(A* a)
{
    std::cout << a->field;
    another_function_which_receives_reference(*a);
    another_function_which_receives_pointer(a);
}

Also, const vs no const works equally well with pointers and references.

Upvotes: 3

Related Questions