My code is as below
fun(int &a)
{
delete &a;
}
main()
{
int *a = new int(10);
fun(*a);
}
Can I delete memory assigned in main function and passed as by reference in fun and deleting memory in fun? Is it the right way?
Reference objects will not be deleted while there are references pointing to them (with a few exceptions you don't have to worry about). When the original reference goes out of scope, the other reference will still point to your object, and the object will remain alive.
Pass-by-reference means to pass the reference of an argument in the calling function to the corresponding formal parameter of the called function. The called function can modify the value of the argument by using its reference passed in.
The only way to fully remove the properties of an object in JavaScript is by using delete operator. If the property which you're trying to delete doesn't exist, delete won't have any effect and can return true.
Can I delete pointers allocated with malloc()? No! It is perfectly legal, moral, and wholesome to use malloc() and delete in the same program, or to use new and free() in the same program.
Do not do this:
I guess this is a Mikey-mouse example but in the real world:
int
in question may not be created by new
- Here is a lot of problemsPlease decide who owns an object. Also if the "person" creates it via new
should be responsible to delete
it.
Check out smart pointers
Short answer: Yes, you can. Do not do it.
References are inmutable, that is, the address (if the compiler implemented the reference as a pointer) is inmutable const. So, if you delete it, the original reference will be pointing to unallocated memory and will crash.
Also, notice that from your code your are passing a reference to the first (and unique) element of the array (if one thinks in pointer as arrays), but fun does not know the size of the array not event that is an array. For example:
fun(int &a)
{
delete &a;
}
main()
{
int a = 42;
fun(a);
}
It will try to delete the address of a reference. Unexpected behaviour.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With