Construct the execution details of a destructor when a C++ function returns an object

  • 2020-04-01 21:33:47
  • OfStack

Look at the following code:


#include<iostream>
class TestConstructor
{
public:
    TestConstructor()
    {
        std::cout<<"TestConstructor()"<<std::endl;
    }
    ~TestConstructor()
    {
        std::cout<<"~TestConstructor()"<<std::endl;
    }
    TestConstructor(const TestConstructor& testObj)
    {
        std::cout<<"TestConstructor(const TestConstructor&)"<<std::endl;
    }
    TestConstructor& operator = (const TestConstructor& testObj)
    {
        std::cout<<"TestConstructor& operator = (const TestConstructor& testObj)"<<std::endl;
        return *this;
    }
};
TestConstructor testFunc()
{
    TestConstructor testInFunc;  //Call TestConstructor() to generate the object testInFunc
    return testInFunc;           //4. Call TestConstructor(const TestConstructor&) to generate temporary objects
                                 //5. Call destructor function to destruct object testInFunc
}
int main()
{
    TestConstructor test;  //Call TestConstructor() to generate the object test
    test = testFunc();     //2 , call testFunc()    //6 , call the equal sign to copy the temporary object to the object test  //7 , call destructor, destruct temporary object 
    return 0;              //8. Call destructor function to destruct object test
}

Look at the output:

< img border = 0 SRC = "/ / files.jb51.net/file_images/article/201302/2013218113225639.jpg" >

There's comments, there's output. The execution details are clear

 

 


Related articles: