c++ - 将 std::bind 与成员函数一起使用,是否为该参数使用对象指针?

标签 c++ c++11 language-lawyer

当使用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) when f is a pointer to a member function of a class T and t1 is an object of type T or a reference to an object of type T or a reference to an object of a type derived from T;

((*t1).*f)(t2, ..., tN) when f is a pointer to a member function of a class T and t1 is not one of the types described in the previous item;

t1.*f when N == 1 and f is a pointer to member data of a class T and t1 is an object of type T or a reference to an object of type T or a reference to an object of a type derived from T;

(*t1).*f when N == 1 and f is a pointer to member data of a class T and t1 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/

相关文章:

c++ - 编译时常量 id

c++ - 如果 'throw' 未能为异常对象分配内存会怎样?

c++ - 显式转换函数、直接初始化和转换构造函数

c - 取数组地址时指针运算结果不同

c++ - 9 月 5 日之后每天执行一个 Action

c++ - 运行 OpenCV_Sample 的 stereo_match.cpp

c++ - 数组和右值(作为参数)

c++ - 非常量数组声明编译错误,C++

c++ - 从左值构造函数调用右值构造函数

c++ - `cname` 和 `name.h` 中的类型可以是不同的类型吗?