[What is the] Best way to pass local variable to function
Depends on why you pass the variable, and what you do with it.
Passing a reference implies that the function does not take ownership of the object, and the function clearly doesn't take ownership, so that's appropriate. Passing a bare pointer is ambiguous about change of ownership so in this case, reference is better.
As I am passing a local variable to the function check1, wouldn't it get out of scope once main terminates and there would be no variable anymore?
Correct. However, whether the object exists after main
returns, is mostly orthogonal to the question of how to pass the object to a function within main
.
Also do realize that after main
returns, the whole program is about to terminate. The only situation where you'd still need an object to exist at that point, is if that object is depended on by a destructor of another object that has static storage.
I found a couple of examples where the operator new is used to allocate memory and return a pointer which is then passed to the function. Is this a better way to do the same task as the variable doesn't get erased?
If you do need to create an object in main
, but need that object to exist after main
has finished, then dynamic allocation is one way to achieve that. Static storage might be an alternative.
In this example however, you delete the object in main, so it gets destroyed just like the local variable does, so in this case, the dynamic allocation offers no advantage.