在Assignment运算符中调用Copy Constructor,需要将左值作为赋值的左操作数

时间:2019-10-04 01:33:03

标签: c++ oop constructor operator-overloading

我正在尝试在赋值运算符重载中调用复制构造函数。我将复制构造函数的结果分配给一个称为temp的指针,然后将 this 指针设置为等温。这个结果给了我错误:左值必须作为赋值的左操作数。我以为这是指向我的对象的指针。为什么将指针重新分配给另一个对象会有问题?

在通过的情况下,我推迟this(* this)并将其设置为temp。对我来说,这意味着我要说的是实际对象等于一个指针。我在误解这个意思吗?

通过情况:

Foo *temp = new Foo(other); //invokes copy constructor
*this = temp;

失败案例:

Foo *temp = new Foo(other); //invokes copy constructor
this = temp;

完整源代码:

TreeNode::TreeNode(TreeNode *other) {
    this->leftChild = other->leftChild;
    this->rightChild = other->rightChild;
    this->data = other->data;
}

TreeNode& TreeNode::operator=(TreeNode *other) {
    if(this != other) {
        TreeNode *temp = new TreeNode(other);
        this = temp;
    }
    return *this;
}

1 个答案:

答案 0 :(得分:0)

1)this是每个类都具有的内置右值表达式(这意味着它不能按照C ++标准进行修改),并且始终指向构成函数的类的实例(对象)打电话。

2)*this始终是左值,即它必须在内存中有一个地址,即它表示可以修改的对象。

因此,当您取消引用时:

*this = temp

您有一个左值,与内存中的空间关联,但不与

this = temp

有关右值和此内容的详细讨论:

What is "rvalue reference for *this"?

Type of 'this' pointer

按原样,此代码似乎有点问题。考虑当您执行以下操作时会发生什么情况:

treenode1 = treenode2;  //assuming both are pointers to TreeNode objects

编译器将看到左值treenode1(在操作期间将始终向其对象“ this”引用),然后看到“ =”,记下重载,然后使用指针treenode2创建对象treenode2指向的对象的新副本。到(将左值temp绑定到新对象),然后尝试将temp中的值复制到原始的treenode1绑定的对象中(我相信现在有三个TreeNode)。

我相信,在完成这种复杂的操作之后,您不希望让临时对象挂起,因为那样会导致内存泄漏。因此,您需要先删除它。因此,如果由于某些原因绝对必须这样做,则解决方案是移动分配运算符,该运算符设计用于临时对象。最好完全避免这种模式,但是似乎很容易造成内存泄漏。