void main()
{
File f;
DoSomething(f);
DoSomething2(&f);
}
void DoSomething(File& f)
{
f.Process();
} // will f go out of scope when this function returns?
void DoSomething2(File* f);
Run Code Online (Sandbox Code Playgroud)
两个问题:
f
本地参考DoSomething
将超出范围,但这显然没有后果.
该f
对象本地main
唯一的结束后超出范围main
(顺便说一下,应该是.int
main
总而言之,引用是对象的别名,但原始对象保留其范围,就像指针一样.
一个常见的建议是尽可能使用引用,必要时使用指针.
一般来说,每当我需要传递一个参数时,我都会使用引用 - duh - 用于引用,以及指针,例如当我希望该参数是可选的1(指针可以是NULL
)时,当我接受数组时,......一般情况下,我会说,在函数中我将使用指针作为指针,而不是一直解除引用它.
NULL
在许多情况下,重载和默认值可能比一个有能力的参数更好.