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);
Two questions:
- As seen in the comment, will f go out of scope when the function returns?
- Do you suggest writing function using reference or pointer? (I’m talking about private functions)
fthe reference local toDoSomethingwill go out of scope, but this obviously has no consequences.The
fobject local tomaingoes out of scope only after the end of themain(which, incidentally, should beintmain.To sum it up, references are aliases to objects, but the original objects retain their scope, as happens with pointers.
A common suggestion is use references when you can, pointers when you have to.
In general I use references whenever I need a parameter to be passed – duh – for reference, and pointers e.g. when I want that parameter to be optional1 (pointers can be
NULL), when I’m accepting arrays, … and in general, I’d say, when in the function I’m going to use the pointer as a pointer, not dereferencing it all the time.NULLable parameter in many situations.