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



以为例

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的实例是在哪里创建的吗?因为当我运行它时,我没有看到打印的施工消息。

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绑定只是使用函数指针的一种非常复杂的方法。它包装指向对象的函数指针,使函数指向对象("对象函数编程")

最新更新