So I was going through a piece of text in C++ and came across the following piece of code:
class example
{
int dataMember;
public:
example& assign(const example& source)
{
if(this!=&source)
{
this->~example();
new (this) example(source);
}
}
};
Okay so I am trying to decode what this function assign is doing. What I have understood yet:
The function takes a constant reference of instance of the class and returns a reference to the class.
Inside the
if
block, firstly the destructor is called for the current instance (As far as I know, current object is destroyed and memory is freed).
Now the main question:
new (this) example(source)
This line is troubling me. What is happening here?
If I am asked to guess, I would say that a new object is being created and is assigned as the current object, as I can infer from this
keyword.
Can anyone clear this up? How exactly are things going on here?
Is this kind of method safe? (If allocation is happening dynamically, programmer will have to deallocate it in future manually)
Thanks.