Good practice is to avoid that type of construct (using the same variable for two different semantics meanings, having reset it in the meantime). It will inevitably create a weird bug later on when you (or somebody else) modify your code and forgets you shared a variable for two different uses.
The only justification would be to spare some memory space but:
- It is very unlikely that you actually need such an optimisation.
- Even if you do, the compiler will usually figure out a variable on the stack is no longer use and can be discarded, the new variable you would create will thus effectively replace the first one. You do not need to care about sparing the memory yourself.
- If your variables are on the heap, you are better off just using two different pointers.
But if you really want to do this reset, you must write a method to do it. There is not built-in way in C++, because it would actually require calling the destructor
and then the constructor
again.
The solution my_struct = Part()
works only if your destructor
is trivial. Let's say you have allocated pointer in your std::vector
, you would have to properly delete
every pointer before emptying the vector
. That's why it cannot be done automatically: the cleanup of the structure may require special treatment rather than plain forgetting.