2

キーワード「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>

4

3 に答える 3

0

しかし、エラーが発生するのか、デストラクタを明示的に呼び出すのが危険なのかはわかりません。提案をしてください。</p>

あなたが書いたコードには、次の 3 つの大きな欠点があります。

  • 読みにくい

  • まれなケース用に最適化されています(実際には自己割り当てを行うことはめったにありませんが、常に自己割り当てチェックを実行します)

  • 例外安全ではありません

copy and swap イディオムの使用を検討してください。

Student & assign(Student stu) // pass stu by value, constructing temp instance
{                             // this is the "copy" part of the idiom
    using namespace std;
    swap(*this, stu); // pass current values to temp instance to be destroyed
                      // and temp values to *this
    return *this;
} // temp goes out of scope thereby destroying previous value of *this

swap がスローされない場合、このアプローチは例外セーフであり、次の 2 つの潜在的な欠点があります。

  • Student がクラス階層の一部である (仮想メンバーを持つ) 場合、一時インスタンスの作成はよりコストがかかります。

  • 自己割り当ての場合、実装はノーオペレーション (または自己等価性テスト) である必要がありますが、その場合、追加のオブジェクト インスタンスが作成されます。自己割り当てのケースは非常にまれです。

于 2013-07-05T13:51:43.890 に答える