c++ - 这些析构函数调用背后的逻辑是什么

标签 c++ c++11

我运行了下面的代码

#include <iostream>
using namespace std;

class Count
{
    private:

        int count;      

    public:

        //Constructor
        Count():count(0) { cout << "Constructor called" << endl; }

        //Destructor
        ~Count() { cout << "Destructor called" << endl; }

        //Display the value.
         Count display() 
         { 
               cout << "The value of count is " << count << endl; 
               return *this;
         }

};

int main()
{
    Count C;
    C.display();
}

结果:-

Constructor called
The value of count is 0
Destructor called
Destructor called

在上面的例子中,析构函数被调用了两次,一次用于销毁“this”对象,一次用于从 main 返回。

我的观察是否正确??

任何人都可以向我解释在此过程中创建的临时对象,例如创建它的原因(如果创建的话)?

最佳答案

您正在从 display() 方法返回一个拷贝,因此它也需要被销毁。因此,在您的主体中,您实际上有 2 个对象,一个是隐含的。

关于c++ - 这些析构函数调用背后的逻辑是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30544694/

相关文章:

c++ - Typedef 适用于结构但不适用于枚举,仅适用于 C++

c++ - std::array 与数组性能

c++ - boost::split 在字符串的开头和结尾留下空标记——这是期望的行为吗?

c++ - 使用 Opengl 在 Window 上显示菜单

c++ - 如何访问子类函数

c++ - 使用子类调用主类中的函数

c++ - 从文本文件中读取行并将字符串放入 vector 中?

c++11 - Arduino 1.6.9/1.610 构建失败,出现 "' constexprint' 未命名类型”

c++ - 通过函数打开流

c++ - 用一个字符制作 std::string 的最佳方法是什么?