visual-studio - Regarding the temporary variable destruction problem generated during initialization of c++ object array?
PHP中文网
PHP中文网 2017-05-16 13:24:00
0
3
863

The first situation:

When creating a C++ object array, if assigned through the initialization list, temporary variables will be generated, but why is the destructor not called?
The code is as follows:

#include <iostream>
    using namespace std;
    class Point
    { public:
        Point():x(0),y(0)
        {   cout<<"Default Constructor called.\n";}
        Point(int xx,int yy):x(xx),y(yy)
        {   cout<< "Constructor called.\n";  }
        ~Point()
        {   cout<<"Destructor called.\n";    }
        void Move(int xx,int yy)    {  x=xx;  y=yy;   }
    private:
        int  x,y;
    };
    int main()
    {
        Point A[2]={Point(1,2),Point()};
        cout<<"hello"<<endl;
        return 0;
    }

The output result is:


Among them, Point A[2]={Point(1,2),Point()}; initializes the object array A through two temporary variables. Why is the destructor not called to destruct it? The result is not The destructors of these two temporary objects were not called.

Second case:
Display calling the constructor for each element of the array, and the destructor will be automatically called:
The code is as follows:

#include <iostream>
using namespace std;
class B
{
    int x, y;
public:
    B();
    B(int i);
    B(int i, int j);
    ~B();
    void Print();
};
B::B() :x(0), y(0)
{
    cout << "Default constructor called.\n";
}
B::B(int i) : x(i), y(0)
{
    cout << "Constructor 1 called.\n";
}
B::B(int i, int j) : x(i), y(j)
{
    cout << "Constructor 2 called.\n";
}
B::~B()
{
    cout << "Destructor called.\n";
}
void B::Print()
{
    cout << "x=" << x << ", y=" << y << endl;
}
int  main()
{
    B *p;
    p = new B[3];
    cout << "*******" << endl;
    p[0] = B();
    p[1] = B(7);
    p[2] = B(5, 9);
    for (int i = 0; i < 3; i++)
        p[i].Print();
    cout << "*******" << endl;
    delete[]p;
}



The running results are as follows:


It can be seen that after calling the constructor initialization for each array element, the temporary variable is destructed.


In summary, both cases are temporary variables, but why one will be automatically destructed and the other will not? Please solve it! ! !

PHP中文网
PHP中文网

认证0级讲师

reply all(3)
黄舟

重新查了一下资料,同时自己动手时实践了一下,更正错误
原因:对象赋值是将右侧的对象的成员的值复制到左边的对象,然后释放右边的对象
——————————
每一次调用B()(有参或无参)都创建了一个临时对象
情况一.创建临时对象(保存在A)后未被赋值,也就不存在释放右侧对象的过程,A中的对象存活至main()结束
情况二.对p数组赋值,创建临时对象赋值给原来的对象,原来的对象(即初始化p时自动创建的临时对象)仅仅是被赋值,右侧的临时变量被析构,delete时析构p中保存的临时对象
——————————
至于为什么A中右侧的临时变量没有被析构,你可以试试在构造函数中输出一下this,然后再输出一下A中保存的对象的引用你就知道了,如果还有错误或不懂请指出,我会及时更正或解答

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!