Consider the following simple code.
struct test
{
test(int n):numelements(n){ arr = new int[numelements] }
int numelements;
int* arr;
~test()
{
delete[] arr;
}
}
void foo_ref(test& x,n)
{
// set first n elements of the array x.arr to random numbers
}
void foo_ptr(test* x,n)
{
// set first n elements of the array x->arr to random numbers
}
int main(void)
{
test mystruct(1000000);
foo_ref(mystruct,20);
// foo_ptr(&mystruct,20);
return 0;
}
In the above code, foo_ref
and foo_ptr
perform exactly the same operations on
the object it refers to viz. mystruct
. However foo_ref passes the object by reference
and foo_ptr by means of pointers.
In both cases where is the destructor of the object invoked? I know the standard answer for this question always is "when the scope of an object ends"
But consider the case of passing by reference. Within the body of foo_ref
mystruct has the scope of that function. So won't the destructor of the object be invoked at the end of the function foo_ref
?
Maybe my confusion has to do with the understanding of the scope of something. Please let me know where I am erring in my reasoning.