我正在玩std::function
和std::bind
以了解如何复制参数以及是否可以保存一些复制操作。
我理解在使用std::bind
时,参数是按值传递的而不是引用(除非指定std::ref
)。但是,当我运行以下代码段时,复制构造函数被调用两次。有人可以解释原因吗?
struct token
{
static int i;
int code;
token()
: code(i++)
{
cout << __FUNCTION__ << ": " << code << endl;
}
virtual ~token()
{
cout << __FUNCTION__ << endl;
}
token (token const & other)
: code (other.code)
{
cout << "copy ctor: " << code << endl;
}
// update -- adding a move ctor
token (token const && other)
: code (std::move(other.code))
{
cout << "move ctor: " << code << endl;
}
// update -- end
void boo() const
{
cout << __FUNCTION__ << ": " << code << endl;
}
};
void call_boo(token const & t)
{
t.boo();
}
int main()
{
token t2;
cout << "default" << endl;
std::function< void () >(std::bind(&call_boo, t2));
cout << "ref" << endl;
std::function< void () >(std::bind(&call_boo, std::ref(t2)));
cout << "move" << endl;
std::function< void () >(std::bind(&call_boo, std::move(t2)));
cout << "end" << endl;
return 0;
}
运行时,会产生以下输出:
token: 1
default
// Without move ctor
// copy ctor: 1 // Makes sense. This is the passing by value.
// copy ctor: 1 // Why does this happen?
// With move ctor
copy ctor: 1
move ctor: 1
~token
~token
ref // No copies. Once again, makes sense.
move
// Without move ctor
// copy ctor: 1
// copy ctor: 1
// With move ctor
move ctor: 1
move ctor: 1
~token
~token
end
~token
答案 0 :(得分:5)
总是复制std :: function的这个构造函数的参数,因此在std :: function中创建了绑定对象的副本(它本身有一个令牌对象的副本)。
http://en.cppreference.com/w/cpp/utility/functional/function/function
template< class F >
function( F f );
5)用f的副本初始化目标。如果f是指向函数的空指针或指向成员的空指针,则*在调用后将为空。这个构造函数不参与重载决策,除非f对于参数类型Args是Callable,并且返回类型为R.(从C ++ 14开始)