0

I have the following piece of code that I have a question about.

f()
{
   static V v(10,0);//first argument is size and the second is init val for each element
    ...
    v = V(5,0);
}

Does the previously allocated V(10,0) get destroyed automatically when I call V(5,0) and assign it to v in the second line ? Or do I have to destroy it ?

Since v is static, is the object V(5,0) retained across function calls ?

marc
  • 797
  • 1
  • 9
  • 26

1 Answers1

1

Does the previously allocated V(10,0) get destroyed automatically when I call V(5,0) and assign it to v in the second line ? Or do I have to destroy it ?

No. The object lives for the life of the application. Its state is changed by the assignment operation.

The object gets destroyed automatically when the application is terminated. You don't have to destroy it. If you try to destroy it, your program will have undefined behavior.


PS You can use better names than v and V to make the code and the discussion more meaningful.

R Sahu
  • 204,454
  • 14
  • 159
  • 270
  • so if the constructor for V is performing dynamic memory allocation, I would need to free that memory by explicitly calling the destructor first in order to clear the previously allocated memory. Then upon calling V again, the constructor will perform dynamic memory allocation again, right ? – marc Aug 16 '17 at 17:52
  • @marc, that's not a good idea to call the destructor. You may need to deallocate and reallocate memory for the data of the object but make sure you don't call the destructor of the object itself in the assignment operator. You may want to take a look at [the copy and swap idiom](https://stackoverflow.com/questions/3279543/what-is-the-copy-and-swap-idiom). – R Sahu Aug 16 '17 at 18:08
  • I call the destructor and then call the constructor in the assignment operation. Because the constructor does dynamic memory allocation, I Would have to free it so that the memory allcoated to V(10,0) can be released. Does that sound correct ? – marc Aug 17 '17 at 23:03