c++析构函数破坏的对象多于构造函数创建的对象

标签 c++ constructor destructor

我正在尝试熟悉 C++ 中的构造函数和析构函数。下面的程序简单地创建了一个复数,将它打印在 stdio 上并退出。我创建了 3 个对象(1. 使用默认构造函数,2. 使用显式构造函数,第三个使用复制构造函数。在退出之前,它销毁了 4 个对象。为什么我下面的程序销毁的对象比构造函数创建的对象多?

#include <iostream>

using namespace std;
class complex
{
private: float a; float b;
public: float real(){return a;};
    float imag(){return b;};

    complex(){a=0.0; b=0.0;cout << "complex no. created."<<endl;};
    complex(float x, float y){a=x; b=y;};
    ~complex(){cout << "complex no. with real part " << this->real() << " destroyed" << endl;};

    void display(){cout << a << '+' << b << 'i';}
    friend ostream& operator<< (ostream & sout, complex c)
    {
        sout << c.a << '+' << c.b << 'i' << "\n";
        return sout;
    }
};
main()
{
    complex c1;
    complex c2(1.0,1.0);

    c1.display();
    cout << endl;
    c2.display();
    cout << endl;
    cout << c2.imag() << endl;
    complex c3 = c2; // this uses the default 'copy constructor'
    c3.display();
    cout << endl;
    cout << c2;
}

我得到的输出是:

complex no. created.
0+0i
1+1i
1
1+1i
1+1i
complex no. with real part 1 destroyed
complex no. with real part 1 destroyed
complex no. with real part 1 destroyed
complex no. with real part 0 destroyed

为了完成,我已经在 CC 和 g++ 编译器上进行了尝试。并且它们的行为相同。

最佳答案

friend ostream& operator<< (ostream & sout, complex c)

正在按值传递复合体,因此正在创建另一个复合体。

将函数参数改为

friend ostream& operator<< (ostream & sout, const complex& c)

这将通过引用传递 complex(保存正在创建和销毁的拷贝)。

const 限定符意味着你的函数不会修改c 的内容。 如果您的函数没有 const 限定符,它就不会接受常量复杂对象,因此以下代码会导致错误(这不是您想要的)。

const complex a_constant_complex(1.0,1.0);
cout << a_constant_complex << endl;

关于您的代码的其他说明

另外,如果可能的话,改掉使用“using namespace std;”的习惯。将整个 std 命名空间拉入全局命名空间并不是一件好事。

并且运算符<<中的尾随 '<< "\n"' 也不应该存在。 operator<< 的目的是将自己发送到流中,如果调用者想要在它之后换行,他们将添加一个 << endl,就像我在常量示例中所做的那样。

关于c++析构函数破坏的对象多于构造函数创建的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18950873/

相关文章:

c# - 完全初始化的类

c++ - 如何调用嵌套类的构造函数

c++ - 当销毁包含该线程的对象时,线程在自身上调用 thread.detach()

c# - 我可以在 C# 中从字符串映射到构造函数吗?

c++ - int/counter 的奇怪行为

c++ - 我可以定义一个环境变量并在条件编译中使用它吗?

c++ - 在模板中比较 == !=

c - 析构函数在 elf 文件中的位置 : not where it should be?

c++ - 类的堆分配对象是否在其范围之后但在 C++ 中调用其析构函数之前仍然存在

c++ - C++中clone系统调用语句出错