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.
I don’t see any
constreferences around here, therefore the answer is “no different in object lifetime between references and pointers”.constreferences bound to temporary expressions have a special rule extending the lifetime of the temporary object, but that doesn’t apply to your code.Your confusion probably stems from a statement made in a very popular FAQ, it goes something along the lines of “a reference IS the referred-to object”. As you can see, this is not true. A reference is separate from the object it refers to, each has its own lifetime (and it’s very rare to see this done correctly, but it’s even legal for the lifetime of the reference to extend longer than the lifetime of the object)