c++中模板对象的构造函数和析构函数是如何调用的

How constructor and destructor called during template object in c++

你能解释一下构造函数和析构函数是如何调用的吗,
因为当我看到 tempravary 对象 4 的析构函数被调用了更多次的输出时

产出
item Args 构造函数调用 1
1 100
item Args 构造函数调用 2
2 教授
item Args 构造函数调用 4
item Args 构造函数调用 3
名为 4
的项目解构器 3 4 教授
名为 4
的项目解构器 名为 4
的项目解构器 名为 3
的项目解构器 名为 4
的项目解构器 名为 2
的项目解构器 名为 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;

}

你错过了复制构造函数。这就是为什么你看到析构函数调用多于构造函数的原因。你也可以用这个代码看到它。


#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);
}

输出

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

https://godbolt.org/z/xhWh9hGr6