boost ::绑定到具有null对象引用的类成员

时间:2015-02-27 12:03:32

标签: boost-bind

采取以下示例

class foo {

public:
   foo() {
    cout << "foo has been constructed" << endl;
   }
   ~foo() {};

   void DoSomething( int i ) {
       cout << "integer = " << i << endl;
   }

};


int main() {
    auto b = boost::bind( &foo::DoSomething,(foo*)0,_1);
    b( 250 );
}

编译好(这并不让我感到惊讶)。但是当我调用b()时,它运行正常。情况怎么样?我期待,因为我没有创建一个foo实例,调用DoSomething会导致运行时问题。

有人可以解释创建foo实例的位置吗?因为当我运行它时,我没有看到打印的构造消息。

1 个答案:

答案 0 :(得分:0)

根本没有创建foo。

boost-bind获取指向该函数的指针。它不关心它是C风格函数,方法还是类函数。 当你给对象实例提升绑定时,它只使用这个对象作为第一个参数。由于DoSomething中不需要任何实例成员,因此您看不到NULL实例的任何影响。

尝试并修改您的示例:

class foo {

    public:
        std:string* test_ptr;
        foo() {
           test_ptr=new std::string("Test");
           cout << "foo has been constructed" << endl;
        }
       ~foo() {};

       void DoSomething( int i ) {
           cout << "integer = " << i << endl;
           cout << this->test_ptr << endl;
           this->*test_ptr = "Test2"; // this is really messy with your example 
       }

       static void DoSomething2 ( foo* sameAsThis_ptr, int i) {
           this->*test_ptr = "Test3"; // compile error

           // same behavior as DoSomething1
           cout << "integer = " << i << endl;
           cout << sameAsThis_ptr->test_ptr << endl;
           sameAsThis_ptr->*test_ptr = "Test4"; // this is really messy with your example 
       }

};
int main() {
    auto b = boost::bind( &foo::DoSomething,(foo*)0,_1);
    b( 250 );

    auto c = boost::bind ( &foo::DoSomething2, (foo*)NULL; _1);
    c( 300 );
}

如果您想了解更多信息,可以仔细查看“函数指针”。 Boost绑定只是一种非常复杂的方法来使用函数指针。 它将函数指针包装到一个对象,使函数成为对象(“对象函数编程”)