【发布时间】:2014-08-20 16:47:41
【问题描述】:
让我证明我的意思。
#include <functional>
#include <iostream>
class MyClass
{
private:
int number;
public:
MyClass()
{
number = 0;
}
void printNumber()
{
std::cout << "number is " << number << std::endl;
number++;
}
};
int main()
{
std::shared_ptr<MyClass> obj = std::make_shared<MyClass>();
auto function = std::bind(&MyClass::printNumber, obj);
function();
// This deallocates the smart pointer.
obj.reset();
// This shouldn't work, since the object does not exist anymore.
function();
return 0;
}
这个输出:
number is 0
number is 1
如果我们像往常一样调用函数,将“function()”替换为“obj->printNumber()”,输出为:
number is 0
Segmentation fault: 11
正如你所期望的那样。
所以我的问题是,是否有任何方法可以确保在对象已被释放时我们无法调用该函数?这与使用智能指针无关,它与普通指针的工作方式相同。
【问题讨论】:
-
没有。也无法验证指针是否指向有效的对象或函数,或者迭代器是否无效。
-
std::bind不会生成std::function。
标签: c++ c++11 std-function stdbind c++14