キーワード「new」の使用方法は 3 つあります。まずは通常の方法です。Student がクラスであるとします。
Student *pStu=new Student("Name",age);
第二の方法。コンストラクターを呼び出さずに、メモリ空間のみを要求します。
Student *pArea=(Student*)operator new(sizeof(student));//
3 番目の方法は「新しい配置」と呼ばれます。メモリ空間を初期化するためにのみコンストラクタを呼び出します。
new (pArea)Student("Name",age);
だから、私は以下のコードを書きました。
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;
}
};
このコードは gcc で問題ありません。しかし、エラーが発生するのか、デストラクタを明示的に呼び出すのが危険なのかはわかりません。提案をしてください。</p>