Re: [問題] operator=裡呼叫destructor

作者: kwpn (ITSST)   2014-11-23 17:23:19
※ 引述《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);
}
作者: saladim (殺拉頂)   2014-11-26 01:08:00
reserve instead of reverse ??

Links booklink

Contact Us: admin [ a t ] ucptt.com