gpt4 book ai didi

c++ - 为什么 STL 算法 for_each 两次调用我的仿函数的析构函数?

转载 作者:太空宇宙 更新时间:2023-11-03 10:21:18 25 4
gpt4 key购买 nike

我正在试验 STL 算法,更具体地说是试验 for_each 函数。我尝试了一个连接字符串 vector 的简单用例。请注意,这可能不是一个好的和/或高效的代码。如果您真的想连接字符串 vector ,请查看 boost::algorithm::join 函数。

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include "concatenator.h"

using namespace std;

int main(int argc, char **argv) {
vector<string> list;
list.push_back("hello");
list.push_back("world");
list.push_back("!!!");
Concatenator concatenator;
for_each(list.begin(), list.end(), concatenator);
cout << "result = " << concatenator.getResult() << endl;
}

连接器类作为常规仿函数实现。

连接器.h:

#include <string>

class Concatenator {
public:
Concatenator();

virtual ~Concatenator();

void operator()(const std::string s);

std::string getResult();
private:
std::string fResult;
};

连接器.cpp:

#include "concatenator.h"
#include <iostream>

Concatenator::Concatenator() :
fResult("") {
}

Concatenator::~Concatenator(){
std::cout << "concatenator destructor called " << std::endl;
}

void Concatenator::operator()(const std::string s) {
std::cout << "concat " << s << " to " << this->fResult << std::endl;
this->fResult += " " + s;
}

std::string Concatenator::getResult() {
return this->fResult;
}

如果你编译并运行这个程序,你会得到以下输出:

concat hello to<br/>
concat world to hello<br/>
concat !!! to hello world<br/>
concatenator destructor called<br/>
concatenator destructor called<br/>
result =<br/>
concatenator destructor called

谁能解释为什么我不能从仿函数中提取正确的结果以及为什么析构函数被调用了这么多次。

最佳答案

std::for_each 按值而非引用获取仿函数对象。然后它按值返回它。换句话说,您的原始仿函数对象永远不会被修改。所以你需要做:

concatenator = for_each(list.begin(), list.end(), concatenator);

顺便说一句,按值传递必然会创建对象的拷贝,因此会调用额外的析构函数。

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

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