gpt4 book ai didi

c++ - 为什么这个仿函数的析构函数被调用两次?

转载 作者:太空狗 更新时间:2023-10-29 23:36:25 26 4
gpt4 key购买 nike

当我运行以下程序时,析构函数被调用两次,我想知道为什么?

#include <iostream>
#include <vector>
#include <algorithm>

class sample
{
public:
sample() { std::cout << "Constructor " << std::endl; }

~sample() { std::cout << "Destructor" << std::endl; }

void operator()(int i)
{
std::cout << i << " , " << std::endl;
}
};

int main()
{

std::vector<int> iNumbers;

for ( int i = 0 ; i < 5 ; ++i)
iNumbers.push_back(i);

std::for_each(iNumbers.begin() , iNumbers.end() , sample() );
}

输出如下

Constructor
0 ,
1 ,
2 ,
3 ,
4 ,
Destructor
Destructor

最佳答案

三违的经典规则。试试这个:

#include <iostream>
#include <vector>
#include <algorithm>

class sample
{
public:
sample() { std::cout << "Constructor " << std::endl; }

sample(const sample&) { std::cout << "Constructor (copy)" << std::endl; }

~sample() { std::cout << "Destructor" << std::endl; }

sample& operator=(const sample&) { return *this; }

void operator()(int i)
{
std::cout << i << " , " << std::endl;
}
};

int main()
{
std::vector<int> iNumbers;

for ( int i = 0 ; i < 5 ; ++i)
iNumbers.push_back(i);

std::for_each(iNumbers.begin() , iNumbers.end() , sample() );
}

输出是:

Constructor
0 ,
1 ,
2 ,
3 ,
4 ,
Constructor (copy)
Destructor
Destructor

关于c++ - 为什么这个仿函数的析构函数被调用两次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15999691/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com