How to delete an instance of a class

Sorry if I have no friggin idea what I am doing. I am trying to delete an instance of the class CONVERSATION, when I call terminate_conversation() member function the code delete this then causes the classes destructor to execute. Then I get the following error, in Visual Studio 2010. Any help would be greatly appreciated!!!

Debug Assertion Failed!

Program C:\Users\Spencer\Desktop\Class_Test\Debug\Class_Test.exe
File: f\dd\vctools\crt_bld\self_x86\crt\src\dbgdel.cpp
Line: 52

Expression: _BLOCK_TYPE_IS_VALID(pHead->BlockUse)



Whats wrong with my code?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
  
#include <iostream>
#include <string>

using namespace std;

class CONVERSATION
{
public:

	CONVERSATION(string caller) { //constructor
		
		m_caller = caller;

		cout << "\nnew call:" << m_caller << endl;
	}

	~CONVERSATION() { //destructor

		cout << m_caller << " terminated" << endl;
	}

	void terminate_call() { //terminate conversation

		delete this;
	}

	string m_caller;

};

int main()
{
	CONVERSATION call("888-888-8888");

	call.terminate_call();
	
	system("pause");

	return 0;
}


This is what I see in the output:


new call:888-888-8888
888-888-8888 terminated

Then the error message pops up
Last edited on
Never delete something you haven't allocated with new. Your code results in undefined behavior.
the reason is the call isn't created with new.

delete this; is certainly not a good thing, since it forces that the object has to be dynamically created (with new).

you can limite the lifetime of an local object with {} like so:
1
2
3
4
5
6
7
8
9
10
11
int main()
{
	{
		CONVERSATION call("888-888-8888");
		// call.terminate_call();
	} // destructor of call
	
	system("pause");

	return 0;
}
PROBLEM SOLVED!!

Thanks guys, here is my new code in my main() function. I can destroy and recreate an instance of the class of the same name in the loop.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
int main()
{

	while(true){

	CONVERSATION* call1 = new CONVERSATION("888-888-8888");
	
	cout << call1->m_caller << endl;

	call1->terminate_call();

	system("pause");

	}

	return 0;
}
Topic archived. No new replies allowed.