Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can we delete an object passed as by reference?

Tags:

c++

c++11

c++14

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?

like image 250
susheel chaudhary Avatar asked Nov 11 '16 07:11

susheel chaudhary


People also ask

What happened when references to an object are removed?

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.

What happens when an object is passed by reference C++?

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.

How to delete an object in js?

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 we use delete with malloc?

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.


2 Answers

Do not do this:

I guess this is a Mikey-mouse example but in the real world:

  1. For a start the int in question may not be created by new - Here is a lot of problems
  2. Who owns the object in question. Not the function. Where is the contract?

Please decide who owns an object. Also if the "person" creates it via new should be responsible to delete it.

Check out smart pointers

like image 176
Ed Heal Avatar answered Sep 29 '22 07:09

Ed Heal


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.

like image 29
LeDYoM Avatar answered Sep 29 '22 09:09

LeDYoM