Formal parameters of functions, when to use references? When to use pointers? When to use pass by value?

In C++, when do you use references for formal parameters of a function? When to use pointers? When to use pass by value?

1 For functions that use the passed value without modification

(1) Small data objects, such as built-in data types or small structures, are passed by value

  void func(int );

(2) If the data object is an array, only pointers can be used, and the pointers are const pointers

  void func(const int *);

(3) If the data object is a larger structure, either a const pointer or a const reference will work

  struct struc{…};

  void func(const struc *);

  或void func(const struc &);

(4) If the data object is a class, use const reference

  void func(const string &,);

2 For the function to be modified using the passed value

(1) If the data object is a built-in data type, use a pointer

  void func(int *);

(2) If the data object is an array, only pointers can be used

  void func(int *);

(3) If the data object is a structure, use a reference or a pointer

  struct struc{…};

  void func(struc *);

  或void func(struc &);

(3) If the data object is a class, use a reference

  void func(ostream &);

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324820579&siteId=291194637