Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
382 views
in Technique[技术] by (71.8m points)

c++ - why destructor is not called implicitly in placement new"?

As referenced in this site... http://www.parashift.com/c++-faq-lite/dtors.html#faq-11.10 But i did not find the reason, why we should explicitly call the desturctor?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can think of it as a call to delete, but since you used placement new, you don't want to use delete, as that would attempt to free the memory. If you wanted it to be called automatically, you could use RAII:

// Could use a templated version, or find an existing impl somewhere:
void destroy_fred(Fred* f) {
   f->~Fred();
}

void someCode()
{
   char memory[sizeof(Fred)];
   void* p = memory;
   boost::shared_ptr<Fred> f(new(p) Fred(), destroy_fred);

   // ...

   // No need for an explicit destructor, cleaned up even during an exception
} 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...