c++ 阻止拷貝構造與拷貝賦值copy constructor & copy assignment operator

ref: C++ primer

struct NoCopy {
    NoCopy() = default;

    NoCopy(const NoCopy&) = delete;
    NoCopy& operator=(const NoCopy&) = delete;

    ~NoCopy() = default;
};

move constructor & move assignment operator

class StrVec {
public:
    StrVec(StrVec&&) noexcept;     // move constructor
    StrVec &StrVec::operator=(StrVec &&rhs) noexcept; // move assignment operator
    // other members as before
};

StrVec::StrVec(StrVec &&s) noexcept   // move won't throw any exceptions
  // member initializers take over the resources in s
: elements(s.elements)
,first_free(s.first_free)
,cap(s.cap)
{
    // leave s in a state in which it is safe to run the destructor
    s.elements = s.first_free = s.cap = nullptr;
}

StrVec &StrVec::operator=(StrVec &&rhs) noexcept
{
    // direct test for self-assignment
    if (this != &rhs) {
        free();                  // free existing elements
        elements = rhs.elements; // take over resources from rhs
        first_free = rhs.first_free;
        cap = rhs.cap;
        // leave rhs in a destructible state
        rhs.elements = rhs.first_free = rhs.cap = nullptr;
    }
    return *this;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章