看板 C_and_CPP 關於我們 聯絡資訊
※ 引述《Caesar08 (Caesar)》之銘言: : #include<algorithm> : #include<vector> : using namespace std; : class A : { : vector<int*> vec; : public: : A(){} : A& operator=(A &&rVal) : { : if(this!=&rVal) : { : this->~A(); : vec=move(rVal.vec); : } : return *this; : } : ~A() : { : for_each(vec.begin(),vec.end(),[](int* &val){delete val;}); : } : }; : int main() : { : A a; : a=A(); : } 除了copy assigment可以用copy and swap idiom, move assignment也可以用。 A::A(const A &rhs) : vec() { vec.reverse(rhs.vec.size()); for (auto &val : rhs.vec) { vec.push_back(new int(*val)); } } A::A(A &&rhs) noexcept : vec(std::move(rhs.vec)) { } A& A::operator=(A rhs) { swap(rhs); return *this; } void A::swap(A &rhs) noexcept { std::swap(vec, rhs.vec); } -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 219.85.199.138 ※ 文章網址: http://www.ptt.cc/bbs/C_and_CPP/M.1416734601.A.339.html
saladim: reserve instead of reverse ?? 11/26 01:08