Home > database >  How constructor and destructor called during template object in c
How constructor and destructor called during template object in c

Time:04-26

Can you please explain how constructor and destructor is called,
Because when i see the output for tempravary object 4 destructor called more times

output
item Args constructor called 1
1 100
item Args constructor called 2
2 Proffecessor
item Args constructor called 4
item Args constructor called 3
item desconstructor called 4
3 4 Professor
item desconstructor called 4
item desconstructor called 4
item desconstructor called 3
item desconstructor called 4
item desconstructor called 2
item desconstructor called 1

#include<iostream>
#include<string>

using namespace std;

template <typename template_type>
class item
{
    string name;
    template_type value;
    public:
        item(string name, template_type value)
        :name{name}, value{value}
        {
            cout<<"item Args constructor called "<<name<<endl;
        }
        ~item()
        {
            cout<<"item desconstructor called "<<name<<endl;
        }
        string get_name()const
        {
            return name;
        }
        template_type get_value()const
        {
            return value;
        }
};


int main()
{

    item<int> item1{"1", 100 };
    cout<<item1.get_name()<<" "<<item1.get_value()<<endl;

    item<string> item2{"2", "Proffecessor" };
    cout<<item2.get_name()<<" "<<item2.get_value()<<endl;

    item<item<string>>  item3{"3", {"4","Professor"}};
    cout<<item3.get_name()<<" "
        <<item3.get_value().get_name()<<" "
        <<item3.get_value().get_value()<<endl;

}

CodePudding user response:

You miss the copy constructor. That's why you see more destructor call than constructor. You can also see it with this code.


#include<iostream>
#include<string>

using namespace std;

template <typename template_type>
class item
{
    string name;
    template_type value;
    
    public:
    item(string name, template_type value):name{name}, value{value}
    {
        cout<<"item Args constructor called "<<name<<endl;
    }
    /* you miss the copy constructor
    item(const item&)
    {
        cout<<"item copy" <<endl;
    }
    */
    ~item()
    {
        cout<<"item desconstructor called "<<name<<endl;
    }
};

void foo(item<int> i){}

int main()
{
    item<int> item1{"1", 100 };
    foo(item1);
}

output

item Args constructor called 1
item desconstructor called 1
item desconstructor called 1

https://godbolt.org/z/xhWh9hGr6

  • Related