且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

c/c ++中何时通过引用传递和何时通过值传递

更新时间:2023-11-11 10:34:16

首选通过引用传递,通常是以下一项或多项:

Prefer pass by reference, usually one or more of:

  1. 如果它很大.(如果是 const,一定要这样做,尽管如此,还是要经常这样做,具体取决于此列表的其余部分)
  2. 如果您想对其进行编辑并使更改全局可见.
  3. 如果您希望虚函数具有多态行为.
  4. 在模板代码中,如果您不知道它将是什么类型.
  1. If it's big. (Definitely do this if it's const, do it anyway quite often though, depending on the rest of this list)
  2. If you want to edit it and make changes globally visible.
  3. If you want virtual functions to behave polymorphicly.
  4. In template code if you don't know what type(s) it's going to be.

传值:

  1. 如果它是一个简单的内置类型(例如 int)
  2. 如果您不希望更改更改原始对象.
  3. 如果您希望能够传入临时变量而不必使其成为常量.