首选通过引用传递,通常是以下一项或多项:
Prefer pass by reference, usually one or more of:
- 如果它很大.(如果是
const
,一定要这样做,尽管如此,还是要经常这样做,具体取决于此列表的其余部分)
- 如果您想对其进行编辑并使更改全局可见.
- 如果您希望虚函数具有多态行为.
- 在模板代码中,如果您不知道它将是什么类型.
- If it's big. (Definitely do this if it's
const
, do it anyway quite often though, depending on the rest of this list)
- If you want to edit it and make changes globally visible.
- If you want virtual functions to behave polymorphicly.
- In template code if you don't know what type(s) it's going to be.
传值:
- 如果它是一个简单的内置类型(例如 int)
- 如果您不希望更改更改原始对象.
- 如果您希望能够传入临时变量而不必使其成为常量.