【发布时间】:2015-01-03 22:45:21
【问题描述】:
由于以下示例,我有这个问题:
#include <utility>
#include <thread>
#include <iostream>
typedef struct foo{
foo() = default;
void operator()(int i) const {}
~foo(){std::cout<<"dtor\n";}
} foo;
typedef struct bar{
bar() = default;
bar(const bar&) {std::cout<<"copy\n";}
bar(bar&&) {std::cout<<"move\n";}
void operator()(const foo& f, int k) const {f(k);}
~bar(){std::cout<<"bar\n";}
} bar;
int main(){
foo f_1, f_2;
bar b_1, b_2;
int i(0), j(0);
while(i++!=2){
std::thread t(b_1, std::cref(f_1), i);
b_2(f_2, j);
t.join();
}
int dummy(0);
std::cin >> dummy;
}
产生(gcc 和 clang 给出相同的结果)
copy
move
bar
bar
copy
move
bar
bar
0
bar
bar
dtor
dtor
,其中 0 是用户输入。
所以 bar 的 dtor——Function 的参数——在胎面完成其工作后(每次迭代)被调用两次。我不明白的是,为什么两次而不是一次(用于制作副本)?
另外,如果仿函数本身持有不可复制的资源或复制成本很高,是否可以避免复制?
谢谢!
更新 它不一定是原始问题的两倍,请参阅下面的 Praetorian 的回答,其中涉及 3 次 dtor 呼叫和 2 次移动。
【问题讨论】:
标签: c++ multithreading c++11 libstdc++ stdthread