vendredi 18 juin 2021

why the constructor and destructor of the same class object are implicitly called multiple times

English is not my native language,so please forgive me for my grammar problems.

When I run my program, I find that class constructors are called when defining objects and explicitly calling constructors。After calling the constructor and after leaving the scope, the destructor is called twice。

#include<iostream>
class test {
private:
    int a;
    int b;
    int c;
public:
    test(int first = 0, int second = 0, int third=0 );
    void show();
    ~test();
};

void test::show() {
    std::cout << this->a<<"\n";
}
test::test(int first , int second , int third ) {
    this->a = first;
    this->b = second;
    this->c = third;
    std::cout << "Construct\n";
}
test::~test() { std::cout << "destruct\n"; }

extern test myclassone;
#include <iostream>
#include "myhead.h"

test myclassone;
int main()
{
    std::cout << "begain\n";
    {
        std::cout << "mid\n";
        myclassone = test(1,1,1);
        std::cout << "mid\n";
        myclassone.show();
    }
    std::cout << "end\n";
}

The output of this program is

Construct
begain
mid
Construct
destruct
mid
1
end
destruct

In my expectation, constructors and destructors will only be called once. But what's puzzling is that according to the output, they were called twice. I've googled this question, and many of the answers have not explained why the constructor is called when the object is defined, and why the destructor is called immediately after the constructor is called

Aucun commentaire:

Enregistrer un commentaire