gpt4 book ai didi

c++ - 为什么在使用 std::bind 时复制构造函数被调用两次?

转载 作者:可可西里 更新时间:2023-11-01 16:39:46 33 4
gpt4 key购买 nike

我正在研究 std::functionstd::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

最佳答案

std::function 的这个构造函数的参数总是被复制,所以在 std::function 中创建绑定(bind)对象的拷贝(它本身有你的 token 对象的拷贝)。

http://en.cppreference.com/w/cpp/utility/functional/function/function

template< class F > 
function( F f );

5) Initializes the target with a copy of f. If f is a null pointer to function or null pointer to member, *this will be empty after the call. This constructor does not participate in overload resolution unless f is Callable for argument types Args... and return type R. (since C++14)

关于c++ - 为什么在使用 std::bind 时复制构造函数被调用两次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50549174/

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