Am I right to say that for
foo1
, the entirevector1
gets copied, and forfoo2
, only the reference tovector1
gets passed into the function?
Correct.
But isn't
vector1
, declared on the stack, supposed to be inaccessible anywhere else (i.e. from insidefoo2
) except the scope in which it was created?
It's just the name of vector1
that is not accessible outside, but you can freely pass its address around (passing it by reference or by pointer). Of course, it continues to exist as long as the function does not return, so returning a pointer to it would be an error (because it would point to a no longer existing object).
This differs from allocation on the heap, that has no scope-bound lifetime or automatic deletion - it's left to you. This is double-edged sword: you can have objects with custom lifetime, but you must remember do actually delete
them when they are no longer needed.
Also, does modifying the contents of
vector1
insidefoo1
,foo2
affect the original vector?
The argument to foo1
is a new, separated vector, any modification done to it will remain local to the function. The argument to foo2
, instead, refers to vector1
, so it will affect the original vector (actually, references are often described as "aliases" for other objects).
And is
vector1
automatically destroyed at the end of its scope, or do we have to delete it manually?
It's automatically destroyed, as any local variable. But: vector2
will have to be deleted manually, since the local object is just the pointer, that has no destructor (by default it doesn't own the object it points to).