There are three way to use keyword 'new'. First is the normal way. Suppose Student is a class.
Student *pStu=new Student("Name",age);
Second way . Only ask for the memory space without calling the constructor.
Student *pArea=(Student*)operator new(sizeof(student));//
Third way is called 'placement new'. Only call the constructor to initialize the meomory space.
new (pArea)Student("Name",age);
So, I wrote some code below.
class Student
{
private:
std::string _name;
int _age;
public:
Student(std::string name, int age):_name(name), _age(age)
{
std::cout<<"in constructor!"<<std::endl;
}
~Student()
{
std::cout<<"in destructor!"<<std::endl;
}
Student & assign(const Student &stu)
{
if(this!=&stu)
{
//here! Is it a good way to implement the assignment?
this->~Student();
new (this)Student(stu._name,stu._age);
}
return *this;
}
};
This code is ok for gcc. But I'm not sure if it would cause errors or it was dangerous to call destructor explicitly. Call you give me some suggestions?