当使用std::bind
绑定(bind)成员函数时,第一个参数是对象的this
指针。但是,它可以将对象作为指针而不是作为指针传递。
例如看下面的程序:
#include <iostream>
#include <functional>
struct foo
{
void bar(int v) { std::cout << "foo::bar - " << v << '\n'; }
};
int main()
{
foo my_foo;
auto f1 = std::bind(&foo::bar, my_foo, 1);
auto f2 = std::bind(&foo::bar, &my_foo, 2);
f1();
f2();
}
clang 和 GCC 都毫无怨言地编译它,结果对两个绑定(bind)都有效:
foo::bar - 1 foo::bar - 2
我一直试图围绕规范(第 20.8.9 节)展开思考,但这是我不太清楚的地方之一。
应该只有一个正确,还是两个都正确?
最佳答案
两者都是正确的。 20.8.9.1.2 转发到 20.8.2 以描述您调用 bind
的要求和效果。 20.8.2 是:
20.8.2 Requirements [func.require]
1 Define INVOKE
(f, t1, t2, ..., tN)
as follows:—
(t1.*f)(t2, ..., tN)
whenf
is a pointer to a member function of a classT
andt1
is an object of typeT
or a reference to an object of typeT
or a reference to an object of a type derived fromT
;—
((*t1).*f)(t2, ..., tN)
whenf
is a pointer to a member function of a classT
andt1
is not one of the types described in the previous item;—
t1.*f
whenN == 1
andf
is a pointer to member data of a classT
andt1
is an object of typeT
or a reference to an object of typeT
or a reference to an object of a type derived fromT
;—
(*t1).*f
whenN == 1
andf
is a pointer to member data of a classT
andt1
is not one of the types described in the previous item;—
f(t1, t2, ..., tN)
in all other cases.
前两个选项允许引用和指针。
这里要注意的重要一点是,措辞确实不将您限制为纯指针。您可以使用 std::shared_ptr
或其他一些智能指针来使您的实例在绑定(bind)时保持事件状态,并且它仍然可以与 std::bind
作为 t1
被取消引用,无论它是什么(当然,假设它是可能的)。
关于c++ - 将 std::bind 与成员函数一起使用,是否为该参数使用对象指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15264003/