explicit destructor

The code below is working fine but i would like to know that the representation of destructor is correct way or not?? I think it would be sort of recursion in line "delete p" in ~myclass() destructor?
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
#include <iostream>
using namespace std;

class myclass{
	int *p;
	string *name;
	public:
	myclass() {
		cout<<"myclass constructed\n";
		p = new int;
		name = new string;
		cin>>*p;
		cin>>*name;
		}
	~myclass() {
		cout<<"myclass destroyed\n"<<*p<<"name:"<<*name<<endl;
		delete p;
		}
};

int main(int argc, char **argv)
{
	myclass *p;
	p = new myclass[3];
	p[1].~myclass();
	return 0;
}

1
2
3
4
5
myclass::~myclass() {
    cout<<"myclass destroyed\n"<<*p<<"name:"<<*name<<endl;
    delete p;
    delete name;
}

new and delete should match each other.

1
2
    p = new myclass[3];
    delete [] p;

Delete an array with the delete [] syntax
Last edited on
You mean that by deleting the p in myclass you might delete the p in main? If that's the case then no, there's no problem. The p in main is different from p[1].p

You do however have a memory leak, since you don't deallocate the memory for name in myclass' destructor

By the way, this is the first time I see a destructor being explicitly called. I didn't even know it would compile...

closed account (zb0S216C)
codeblock wrote:
1
2
p = new myclass[3];
p[1].~myclass();
Do not do this. Never call the destructor explicitly unless the object was created through placement "new". The reason why you should not call the destructor is because the compiler will implicitly call the destructor for you. If you call the destructor, the compiler will still call the destructor regardless, thereby destroying an invalidated object -- not good.

Wazzak
Last edited on
yes absolutely agree with you Framework but,
1
2
3
myclass *p;
p = new myclass[3];
p[1].~myclass();

in the above code the line p = new myclass[3] is going to create object through "new" if i am not wrong.

"If you call the destructor, the compiler will still call the destructor regardless, thereby destroying an invalidated object."

I am not able to getting you. even if here i have created object with new.
So why should we do not call destructor explicitly in this case? If so then, Is there any other way to destruct the one element of the array and not the entire array?
There you are creating the objects with the new operator, not placement new. The destructor will be automatically called when you use delete[].

Why do you want to destruct that one object? That seems strange to me.
is there any other way to destruct the one element of the array and not the entire array?

Plain arrays do not offer this functionality, but you can (and should) use vector::erase(), as in http://www.cplusplus.com/reference/stl/vector/erase/
which uses an allocator to encapsulate the placement new.

I find p = new int; offensive.
Topic archived. No new replies allowed.