复制构造函数调用无限循环,尽管通过引用调用

Ale*_*sie 3 c++ copy-constructor

调用循环的代码:

Foo temp = Foo(token.substr(0,i));
this->leftExpression = temp;
Run Code Online (Sandbox Code Playgroud)

已经Foo声明为:

class Foo{
    private:
        std::string expr;
        std::vector <Bar*> tokens;
        std::vector <std::string> stringtoken;
Run Code Online (Sandbox Code Playgroud)

并且CCTOR调用循环:

Foo::Foo(const Foo& a_expr){
    this->expr = a_expr.expr;
    this->tokens = a_expr.tokens;
    this->stringtoken = a_expr.stringtoken;
}
Run Code Online (Sandbox Code Playgroud)

什么是调用这个循环?

编辑:

作业运营商:

Foo& Foo::operator=(const Foo& a_expr){
    Foo temp(a_expr);
    std::swap(*this, temp);
    return (*this);
}
Run Code Online (Sandbox Code Playgroud)

Mik*_*our 5

问题出在这里:

std::swap(*this, temp);
Run Code Online (Sandbox Code Playgroud)

std::swap使用赋值的默认实现,因此从赋值运算符调用它时的无限递归.

如果你真的需要编写自己的赋值运算符,那么编写自己的赋值运算符,swap例如:

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);
}
Run Code Online (Sandbox Code Playgroud)

在这种情况下,看起来所有成员都可以正确复制(尽管你可能需要注意愚蠢的指针tokens).如果是这种情况,则根本不需要编写自己的析构函数,复制构造函数或复制赋值运算符 - 只需让隐式函数执行正确的操作即可.