1

I'm hoping that this isn't an utterly ignorant question, but I can't seem to find any information on a few snippets of code I've been coming across.

Instead of describing it, I'll just give an example:

auto x = reinterpret_cast<T*>(something->data * sizeof(T));
myResult = std::move(*x);
x->~T();

Note that this code exists within a template class, hence the T.

I have a general understanding of reinterpret_cast<> and std::move(). However, I don't quite understand what the statement x->~T() means. Being more familiar with C, I thought it was a logical not of the returned value of <datatype>(). Looking at the syntax though, it makes more sense - to me at least - that it's a destructor of some sorts.

If anyone could shed some light on this, it would be appreciated.

Mlagma
  • 1,240
  • 2
  • 21
  • 49
  • Yes, it's an explicit destructor call. – T.C. Jul 27 '15 at 20:13
  • x->~T(); is calling the destructor of T (which can be class A or B or C), whatever the class was declared as. –  Jul 27 '15 at 20:16
  • 2
    `something->data * sizeof(T)` ... what? Multiplication, followed by a `reinterpret_cast`? That is a ... strange operation. Throw in a + somewhere and it might make sense. – Yakk - Adam Nevraumont Jul 27 '15 at 20:17
  • As some of the others have said in the comments here, it's an explicit destructor and the reason it's being called can be found here: http://stackoverflow.com/questions/20589025/why-is-the-destructor-call-after-the-stdmove-necessary – Brandon Haston Jul 27 '15 at 20:19
  • This example is insufficiently example-like to know what your program is supposed to do. But, yes, this is obviously a destructor call. The original object was probably constructed with _placement new_, someplace else. – Lightness Races in Orbit Jul 27 '15 at 20:22

1 Answers1

1

It's an explicit destructor, and it's is usually used in conjunction with placement new. Placement new overlays an object (instantiates an object) in memory that had been pre-allocated, and calls the constructor thereafter(see wiki article).

Werner Erasmus
  • 3,988
  • 17
  • 31