std::bind创建的函子在哪里?
Where do std::bind-created functors live?
函数指针可以指向自由函数、函数对象、成员函数调用的包装器中的任何对象。
然而,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;
}
std::bind
按值返回一个对象(对象的确切类型是标准库的实现细节)。该对象存储所有必需的状态,其析构函数执行所有必需的清理。
注意你的vector不存储指针——它存储std::function
对象。std::function
对象在内部存储创建它的对象(在您的例子中是std::bind
返回的函数指针或对象),并且它的析构函数正确地销毁存储的对象。销毁指向函数的指针没有任何作用。销毁类类型的对象将调用其析构函数。
std::bind
函数创建一个未指定类的实例,当该对象超出作用域并被销毁时,该实例的存储空间也将被销毁。
就像其他类的实例一样,通过析构函数释放资源
相关文章:
- C++我需要了解在哪里使用指针和双指针
- 未定义的引用在哪里
- 谷歌测试中的期望值存储在哪里
- 尽管遵循了规则,内存泄漏在哪里
- 静态数据成员模板专用化的实例化点在哪里
- 在哪里放置我的函数?进入我的母语 Gui 还是进入我的演示者?
- 在哪里声明结构运算符重载
- C++ 中的自定义异常:在哪里定义它们?
- 常量参数存储在哪里 (C++)?
- 如何在 c++ 中确定一条指令(以字节为单位)在哪里结束,另一条指令从哪里开始?
- 此递归函数的每次迭代的值存储在哪里?
- 如何告诉本机节点模块所需的dll存储在哪里?
- 在哪里存储跨平台C++应用存储?
- C++泛型类错误,问题出在哪里?
- 在标准中,模板参数的语法在哪里定义,例如,'std::function<int(char)>'?
- 将类作为主要参数的语法在哪里需要?
- 模板参数在 C++ 中存储在哪里?
- 我的重复检查代码中的错误究竟在哪里?
- 在哪里可以找到 std::bitset 的数据成员?
- std::bind创建的函子在哪里?