C++: can the object be destroyed earlier, to make its storage memory be reused by subsequent objects?
In one segment of C++ code, at the 1st half part, objects a, b are used; at the 2nd half part, objects c, d are created and used.
Since objects a, b take a lot of memory, I want to manually destroy objects a, b when the 1st half part finishes.
I know I can use new, delete to achieve it.
But if I do not use new, and still want to destroy objects earlier (that means, before the time of its end of scope), can I manually call its destructor to destroy it? So that part of memory can be reused for object c and d. (I do not need to release the memory since reuse is fine.
Here is a pseudo code:
monsterClass a, b;
dragonClass c, d;
int i,j,k,l;
a = monsterClass(1000, 2000);
b = monsterClass(2000, 3000);
i = processMethod1(a, b);
j = ...;
k = ...;
l = ...;
// here, I want to destroy a, b, since they are not used any more, while occupy memory.
// The above half part and the below half part use many common variables.
// So it seems scope {} method makes it inconvenient,
// since I don't want to create a function with too many parameters.
// I don't want to use new or delete here. I hope it looks simple and not prone to error
// So can I use: ~a, ~b here?
c = dragonClass(400, 3000);
d = dragonClass(500, 4000);
processMethod2(c, d, i);
j = ...;
k = ...;
l = ...;
[Update 1] So most people suggest to use scope, which is a good way. I am just still very curious, can I use ~a and ~b there? I think it seems to be a feasible and convenient way, too.
[Update 2] I come up another situation. In this situation, the scopes of different variables are interwined! It is like this: the scope of a has an overlap of scope of b, but they are not including relationship. It is overlap partly relationship. In this case, does this mean using scope is not possible? And the last resort is to use new and delete, right?
As your code snippet, you could write as