为什么绑定不适用于按引用传递?
Why does bind not work with pass by reference?
我发现在使用 std::bind 时按引用传递往往不起作用。这是一个例子。
int test;
void inc(int &i)
{
i++;
}
int main() {
test = 0;
auto i = bind(inc, test);
i();
cout<<test<<endl; // Outputs 0, should be 1
inc(test);
cout<<test<<endl; // Outputs 1
return 0;
}
为什么当通过使用 std bind 创建的函数调用时变量不递增?
std::bind
复制提供的参数,然后将副本传递给您的函数。为了传递对 bind
的引用,您需要使用 std::ref
:auto i = bind(inc, std::ref(test));
我发现在使用 std::bind 时按引用传递往往不起作用。这是一个例子。
int test;
void inc(int &i)
{
i++;
}
int main() {
test = 0;
auto i = bind(inc, test);
i();
cout<<test<<endl; // Outputs 0, should be 1
inc(test);
cout<<test<<endl; // Outputs 1
return 0;
}
为什么当通过使用 std bind 创建的函数调用时变量不递增?
std::bind
复制提供的参数,然后将副本传递给您的函数。为了传递对 bind
的引用,您需要使用 std::ref
:auto i = bind(inc, std::ref(test));