代码之家  ›  专栏  ›  技术社区  ›  Sam

std::bind创建的函子在哪里?

  •  7
  • Sam  · 技术社区  · 11 年前

    函数指针可以指向任何对象,包括自由函数、函数对象、成员函数调用的包装器。

    但是,std::bind创建的函子可以具有状态,也可以具有自定义创建的状态。该状态被分配到哪里,谁在删除它?

    考虑以下示例-删除向量时,状态(数字10)是否会被删除?谁知道在函子上调用删除器,而在函数指针上不调用删除器?

    #include <iostream>
    #include <functional>
    #include <vector>
    using namespace std;
    using namespace std::placeholders;
    class Bar
    {
        public:
        void bar(int x, int y) { cout << "bar" << endl; }
    };
    void foo(int baz){ cout << "foo" << endl; }
    int main() {
        typedef std::function<void(int)> Func;
    
        std::vector<Func> funcs;
        funcs.push_back(&foo); // foo does not have to be deleted
        Bar b;
        // the on-the-fly functor created by bind has to be deleted
        funcs.push_back(std::bind(&Bar::bar, &b, 10, _1)); 
    
        // bind creates a copy of 10. 
        // That copy does not go into the vector, because it's a vector of pointers.
        // Where does it reside? Who deletes it after funcs is destroyed?
    
        return 0;
    }
    
    2 回复  |  直到 11 年前
        1
  •  10
  •   Angew is no longer proud of SO    11 年前

    std::bind 按值返回对象(对象的确切类型是标准库的实现细节)。此对象存储所有必需的状态,其析构函数执行所有必需的清理。

    请注意,您的向量不存储指针-它存储 std::function 物体。A. std::函数 对象内部存储创建它的对象(函数指针或 std::绑定 在您的情况下),其析构函数正确地销毁存储的对象。销毁指向函数的指针无效。销毁类类型的对象会调用其析构函数。

        2
  •  2
  •   Some programmer dude    11 年前

    这个 std::bind 函数创建一个未指定类的实例,当该对象超出作用域并被销毁时,该实例的存储也会被销毁。

    就像任何其他带有析构函数的类的实例一样,释放了一些资源。