Rules for using links in C ++

Possible duplicate:
How to pass objects to functions in C ++? Why follow a const link instead of a value?

In C ++, is there some kind of rule or indication of when exactly one should or should at least choose to use links by links rather than by value?

And if we are talking about the size of an object with some kind of object, as far as is known (few honestly), it can be difficult to judge.

+8
c ++
source share
4 answers

You must pass by reference whenever you want the argument changes to be visible outside the function. This pass by reference is not const and is mainly due to logic, not efficiency.

You should go through the link (mainly const ) when you are dealing with data types that are larger than the register. Since the link is basically const , you cannot make any changes to it, therefore it is motivated by efficiency.

+7
source share
  • If you do not want to refer to the copy constructor of the object (for example, if so, due to the size of the object).
  • When you really need a link, not just a value ( swap(a,b) , for example, since you really need the source links to make the swap.)
+3
source share

I usually use pass by reference in the following situations:

1) objetc is larger than the pointer: in this case, if I do not want to change objetc, use the const link:

 Reference object; foo(object); 

with foo declared as:

 void foo(const Reference & object); 

2) For the code, try to avoid such ticks:

 int f1 = xxx; int f2 = yyy; int f3 = zzz; .... foo(f1, f2, ............) 

using struct:

 struct X { int f1; int f2; int f3; .... }; X x; x.f1 = xxx; ..... foo(X); 

with foo defined as:

 foo(const X & x); 

3) to speed up the fill: remember that calling functions must put parameters on the stack 4) You need to change the parameters inside the function.

 Reference object; foo(object); 

with foo declared as:

 void foo(Reference & object); 
+3
source share

Preferred pass-by-reference-to-const - pass-by-value . Passing by value is an expensive operation because copies of the object are made using copiers. Also, if you have some non-primitive data members in a class (for example: std::string ), every time a new class object is created, those std::string objects will also be created.

Passing by reference also avoids the slicing problem . If you pass an object of a derived class by the value of a function that expects an object of the base class, the derived functions of the derived class will be truncated and the object inside the function will behave like an object of the base class. If you follow the link, you can avoid slicing.

However, there are times when you cannot follow the link. If function arguments or return value must be NULL, you cannot use references.

+1
source share

All Articles