【问题标题】:Pointer to class object in overloading prefix and postfix operators重载前缀和后缀运算符中指向类对象的指针
【发布时间】:2017-09-22 13:50:14
【问题描述】:

我在一个类中重载了前缀和后缀递增/递减运算符。

#include <iostream>
using namespace std;

class X
{
public:
X() { cout << "X" << endl;}
~X() { cout << "~X" << endl; }

X& operator++() { X *x = new X; return *x; }
X operator++(int) { X *x = new X; return *x; }
X& operator--() { X *x = new X; return *x; }
X operator--(int) { X *x = new X; return *x; }
};

int main()
{
X p;
cout << endl;
++p;
cout << endl;
p++;
cout << endl;
return 0;
}

输出是:

X

X

X
~X

~X

似乎在使用后缀增量时,对象会被实例化并删除,但在使用前缀增量时,它不会被删除。

这种行为的原因是什么?

【问题讨论】:

  • 你为什么在这里使用new

标签: c++ operator-overloading


【解决方案1】:

您的后缀运算符按值返回,因此您使用new 创建的对象被复制,并且由于您没有将其绑定到任何内容,因此该副本在main 中的后缀表达式末尾被销毁。通过让复制构造函数输出一些东西,您可以观察到这种行为,例如参见here

另一方面,您给运算符添加前缀只是返回对您使用new 分配的对象的引用,因此在main 中的表达式结束时,只有引用被销毁。

在这两种情况下,您都会泄漏new 分配的内存。

【讨论】:

    【解决方案2】:

    后缀版本返回X的实例,而不是对实例的引用,所以调用了这个副本的析构函数。无论如何,你不应该在你的运营商中使用new

    X& operator++() { return *this; }
    X operator++(int) { X x; return x; }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-01-05
      • 2016-03-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多