赋值运算符在不应该返回"empty"实例时返回?
Assignment operator is returning an "empty" instance when it shouldn't?
我正在实现一个堆栈只是为了练习。那么,在main中,我有这样的东西:
Stack stack;
stack.push(element1;
stack.push(element2);
Stack copy;
copy = stack;
所以我重载赋值操作符,因为我还想生成新的元素实例(而不仅仅是将每个元素的指针从一个复制到另一个),如下所示
Stack &Stack::operator=(const Stack &toCopy) {
Stack* stack = new Stack;
if (toCopy.first == NULL) return *stack;
for (Node* actual = toCopy.first; actual != NULL; actual = actual->sig) {
stack->push(actual->elem);
}
// In this state, *stack has 2 elements as it should
return *stack;
}
回到主程序中,copy变量没有得到更改…它仍然是空的,好像约会从未发生过。就好像我只做了Stack copy;
,你能解释一下这里发生了什么吗?
您没有修改当前对象(即*this
)。
你只是通过new
创建一个新对象,然后返回它。注意,对于copy = stack;
,它相当于copy.operator=(stack);
,注意返回值不被使用,它只是被丢弃(并导致内存泄漏),并且copy
没有改变。
你应该这样做:
Stack &Stack::operator=(const Stack &toCopy) {
// do some work to clear current elements in *this
// ...
// add elements from toCopy
for (Node* actual = toCopy.first; actual != NULL; actual = actual->sig) {
this->push(actual->elem);
}
// operator= is supposed to return *this in general
return *this;
}
您可能误解了赋值操作符。它在等号左边的对象上下文中起作用。所以你的::operator=(...)
应该总是在*this
上工作,也应该总是返回*this
。
您发布的operator=(...)
正在操作您在堆上分配的新堆栈对象,并且您正在操作它而不是*this
。
您可以有效地将代码中的stack
替换为this
。例如:
Stack &Stack::operator=(const Stack &toCopy) {
//Stack* stack = new Stack; // Don't do this.
if (toCopy.first == NULL) return *this;
for (Node* actual = toCopy.first; actual != NULL; actual = actual->sig) {
this->push(actual->elem); // You could also just call push without "this->"
}
// In this state, *stack has 2 elements as it should
return *this;
}
相关文章:
- 返回的指针属性中类实例上的矢量属性消失
- 返回 C++ 中的指针实例变量
- 在实例化之前推断函数模板的返回类型
- 返回引用实例和非引用实例(return mystr & vs mystr)之间的区别是什么?
- 当函数返回C++向量实例时,它正在运行
- 实例化对象并调用方法,使用单行语法在 C# 或 C++ 中返回值?
- 如何实例化类的公共成员并将其作为 std::p romise 返回?
- 是否是从等待返回到悬而未决的"this"实例的未定义行为?
- 返回实例变量的c++方法可以访问变量中的数据,但不能更改它,但在编译时不会生成错误
- 我们可以在没有新实例化的情况下声明一个抽象方法来返回抽象超类中的子类对象吗
- 是否可以从派生类返回基类的实例?
- 返回具体子类实例的 C++ 虚拟类函数
- 当模板返回类型阻止其实例化时,如何向用户提供漂亮的static_assert消息?
- 如何在 C 中包装C++具有参数的类方法或返回另一个C++类的实例?
- 从新实例的向量中检索数据返回 0
- 返回实例导致"尝试引用已删除的函数"错误
- 此构造函数是否返回实例
- 从方法堆栈编译中按值返回实例
- 模板方法编译错误,从内部类返回实例
- 继承和返回实例的循环依赖性问题