Re: Deleting a passed-by-reference object in a function
Hi David,
Thanks for your reply
I agree that the code is poor style and infact I dont expect any situations
to do this kind of thing. But, I found this in a complex piece of code that
somewhat translated to this case, so I wrote this code snippet to get a
clear picture of this, by checking the value of the memory location pointed
by the variable after it has been passed to the function.
So, just for the sake of my own knowledge, I wanted to know if this thing is
perfectly legal in C++ or not. It is working fine in VC, but can this be
considered something specific to the implementation of the compiler, and is
it possible that this might break on some other platform?
Besides that, why should it be "delete [] pCalled;" when it is not an array
and pCaller is just a scalar pointer-variable?
Thanks very much,
Shoaib.
"David Wilkinson" <no-reply@effisols.com> wrote in message
news:eC1wlwEhIHA.3352@TK2MSFTNGP04.phx.gbl...
M. Shoaib Surya wrote:
Hello,
Is it okay to delete an new'ed object in the function that has been
passed-by-reference.
Please check the statement "delete pCalled;" in the following code
snippet.
void Test(int& i)
{
int* pCalled = &i;
printf("Address in Called: %d\n", pCalled);
delete pCalled;
}
int main()
{
int* pCaller = new int(10);
printf("Address in Caller: %d\n", pCaller);
Test(*pCaller);
}
The thing is that it is running fine in VC and the pointer also has the
same value. But, what I am wondering is that is it possible that this is
a platform-specific implementation of the compiler and this code might
break on other platforms, or is it a defined behavior and perfectly legal
in C++?
Shoaib:
Shouldn't it be
delete [] pCalled;
?
But why don't you pass the pointer directly? Using a reference here may
work, but why do it?
Also, I find this code poor style. Why not just delete the pointer in the
caller? Even better, use std::vector.
--
David Wilkinson
Visual C++ MVP