470,815 Members | 1,284 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 470,815 developers. It's quick & easy.

Placement new and destructor

Hello all,

I am reading C++ Primer 3rd edition by Lippman & Lajoie and come across
the following piece of code as an example demostrating the use of
placement new.

Section 8.4.5 (Page 417-418)

#include <iostream>
#include <new>

const int chunk = 16;

class Foo {
public:
int val() { return _val; }
Foo() { _val = 0; }
private:
int _val;
};

char *buf = new char[sizeof (Foo) * chunk];

int main() {
Foo *pb = new (buf) Foo;
if ( pb.val() == 0 )
cout << "new expression worked!" << endl;
delete[] buf;
return 0;
}

Looking at the above code, I feel it is incorrect at 2 places.

1. Since pb is a pointer to a Foo object, the expression inside the if
condition should have been pb->val() instead of pb.val(), okay that may
be a printing mistake.

2. The second error is not a typographical error. I see at no place in
the code the destructor of the Foo object is called. Instead delete[]
buf calls the destructors of 16 char objects which is fine but I feel
there should be a call to Foo's destructor before the delete[] buf.
Shouldn't there be a call to pb->~Foo() before delete[] ?

Please tell me, if I am missing something as this book is rated highly
recommended at accu.org.

Thanks

May 10 '06 #1
1 3702
wij
dragoncoder wrote:
int main() {
Foo *pb = new (buf) Foo;
if ( pb.val() == 0 )
cout << "new expression worked!" << endl;
delete[] buf;
return 0;

} Looking at the above code, I feel it is incorrect at 2 places. 1. Since pb is a pointer to a Foo object, the expression inside the if
condition should have been pb->val() instead of pb.val(), okay that may
be a printing mistake. 2. The second error is not a typographical error. I see at no place in
the code the destructor of the Foo object is called. Instead delete[]
buf calls the destructors of 16 char objects which is fine but I feel
there should be a call to Foo's destructor before the delete[] buf.
Shouldn't there be a call to pb->~Foo() before delete[] ?


I think you are correct.

int main() {
Foo *pb = new (buf) Foo;
//if ( pb.val() == 0 ) // the new above will throw if failed
// so this test always yields false
cout << "new expression worked!" << endl;
pb->~Foo() // yes, destruct *pb
delete[] buf;
return 0;
}

May 10 '06 #2

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

11 posts views Thread by Peter Olcott | last post: by
23 posts views Thread by Giancarlo Niccolai | last post: by
20 posts views Thread by Ioannis Vranos | last post: by
3 posts views Thread by ma740988 | last post: by
5 posts views Thread by removeps-generic | last post: by
15 posts views Thread by LuB | last post: by
reply views Thread by mihailmihai484 | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.