为什么为这个仿函数调用两次析构函数?

nsi*_*akr 2 c++ foreach stl

当我运行以下程序时,析构函数被调用两次,我试图理解为什么?

#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() );
}
Run Code Online (Sandbox Code Playgroud)

输出如下

Constructor
0 ,
1 ,
2 ,
3 ,
4 ,
Destructor
Destructor
Run Code Online (Sandbox Code Playgroud)

Dav*_*rtz 5

经典规则三违规.试试这个:

#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() );
}
Run Code Online (Sandbox Code Playgroud)

输出是:

构造
0,
1,
2,
3,
4,
构造(复制)
析构
析构