Copy constructor invokes infinite loop although having call by reference

c++, copy-constructor

Solution

The problem is here:

std::swap(*this, temp);

The default implementation of `std::swap` uses assignment, hence the infinite recursion when calling it from your assignment operator.

If you really need to write your own assignment operator, then write your own `swap`, for example:

void Foo::swap(Foo & other) {
    using std::swap;
    swap(expr, other.expr);
    // and for all other members
}

Foo& Foo::operator=(Foo temp){
    this->swap(temp);
    return (*this);
}

In this case, it looks like all the members are correctly copyable (although you might need to be careful of the dumb pointers in `tokens`). If that is the case, then there's no need to write your own destructor, copy constructor or copy-assignment operator at all - just let the implicit ones do the right thing.

Problem

The code invoking the loop: ``` Foo temp = Foo(token.substr(0,i)); this->leftExpression = temp; ``` Having `Foo` declared as: ``` class Foo{ private: std::string expr; std::vector <Bar*> tokens; std::vector <std::string> stringtoken; ``` And the CCTOR invoking the loop: ``` Foo::Foo(const Foo& a_expr){ this->expr = a_expr.expr; this->tokens = a_expr.tokens; this->stringtoken = a_expr.stringtoken; } ``` What is invoking this loop? EDIT: Assignment operator: ``` Foo& Foo::operator=(const Foo& a_expr){ Foo temp(a_expr); std::swap(*this, temp); return (*this); } ```

Original source

Related problems