I'm new on StackOverflow and my first question is abot what happens to a running method, when I delete its object? Furthermore, what happens when I create a new object in the method, after I deleted the old one?
There's a small code snippet below to clarify my question. (Programming in C++11)
// Declaration and Definition of the class
class MyClass{
private:
static int counterFromClass = 0;
int counterFromObject;
public:
MyClass() {
counterFromObject = 0;
}
void ~MyClass() {}
void doSomething();
};
// Somewhere in the code a new object of the class is generated like this:
MyClass object = new MyClass();
// Then the method is called:
object->doSomething();
// Definition of the method
void MyClass::doSomething() {
this->counterFromObject++;
delete object;
MyClass object = new MyClass();
this->counterFromClass++;
}
If now the method doSomething() is called:
- Will the method run until its end or will it be interrupted?
- If it runs until the end, does it belong to the deleted
objector the new one? Both objects, the deleted and the new one, have the same name. - If it is interrupted, what will happen? Or is this behaviour undefined?
So far what I have expirienced, it seems that the method will run to its end and execute all commands on its way, as long as they don't affect the deleted object. E.g. manipulating a static variable like counterFromClass is allowed. And it seems also possible to manipulate data members of the object like counterFromObject inside the method, as long as they are manipulated before the delete command.
Well, the code works but I know that it's not the best programming style. So I just started to work on a better solution, but I still got curious what exactly happens and if my thougths were correct. I would be grateful for answers.
If something's wrong with the question, please let me know because I am not that familiar with asking questions on StackOverflow yet.
Thank you :)