lundi 4 juin 2018

Move constructor c++ in push back of vector

Why the following code doesn't work?
why I can't perform push back in this code?
I try to simulate the move operator.
I have passed the check of the compiler, but I still cannot run this code.

struct test{
explicit test(const int &i2) : i(new int(i2)){}
test() = default;
test(const test &t2) : i(new int(*(t2.i))) 
{}
test(test &&other) : i(nullptr) 
{
    i = other.i;
    other.i = nullptr;
//  *this = std::move(other);
}
int* i;
test& operator = (test&);
// move assign
test& operator = (test&&);
~test(){
    if(i != nullptr) delete i;
  };
};
// copy operator
test& test::operator = (test& t)
{   
    if(this != &t){
        delete i;
    i = new int(*(t.i));
 }
   return *this;
}
// move operator
test& test::operator = (test&& other){
    if(this != &other){
        delete this->i;
        this->i = other.i;
        other.i = nullptr;
    }
    return *this;
}

using namespace std;
int main(){
    vector<test> v;
    v.push_back(test(25));
    return 0;
}

Aucun commentaire:

Enregistrer un commentaire