强制超出作用域boost::bind失败
Force out of scope boost::bind to fail
我试图创建一个绑定boost::函数到超出作用域的成员函数的示例。即使对象不再存在,仍然可以调用该函数。
我需要证明这不是一个正确的使用,应用程序需要失败。但是内存位置似乎仍然是正确的,所以我需要一种方法使它失败。
另一个问题是:我对吗?我是不是漏掉了什么?
class bad_object {
public:
void fct1() {cout << "Fct 1 called. String value: " << sth << endl;};
void fct2(int i) {cout << "Fct 2 with param " << i << endl;};
string sth;
};
int main()
{
bad_object b;
boost::function<void ()> f1(boost::bind( &bad_object::fct1, b ));
boost::function<void ()> f2(boost::bind( &bad_object::fct2, b, 10 ));
boost::function<void ()> f3;
{
bad_object c;
c.sth = "There once was a cottage";
f3 = boost::bind( &bad_object::fct1, c );
}
// c now goes of scope, f3 should therefore be invalid
f3();
return 0;
}
按预期输出。
Fct 1 called. String value:
Fct 2 with param 10
Fct 1 called. String value: There once was a cottage
也许您使用weak_ptr
: Live On Coliru
#include <boost/shared_ptr.hpp>
#include <boost/weak_ptr.hpp>
#include <boost/smart_ptr/make_shared.hpp>
#include <boost/bind.hpp>
#include <boost/function.hpp>
#include <iostream>
struct X
{
int foo() const
{
return 42;
}
virtual ~X() {
std::cout << "I'm stepping out heren";
}
};
int weak_call(int (X::*ptmf)() const, boost::weak_ptr<X> const& wp)
{
auto locked = wp.lock();
if (!locked)
throw boost::bad_weak_ptr();
return ((*locked).*ptmf)();
}
int main()
{
boost::function<int()> bound_foo;
{
auto x = boost::make_shared<X>();
bound_foo = boost::bind(weak_call, &X::foo, boost::weak_ptr<X>(x));
std::cout << "Bound foo returns: " << bound_foo() << "n";
}
std::cout << "Bound foo returns: " << bound_foo() << "n";
}
打印:
Bound foo returns: 42
I'm stepping out here
terminate called after throwing an instance of 'boost::bad_weak_ptr'
what(): tr1::bad_weak_ptr
一个更通用的版本(允许n元成员函数,可选的const
限定)在这里(要求c++11): coliru
相关文章:
- 如果没有malloc,链表实现将失败
- 模板参数替换失败,并且未完成隐式转换
- 具有默认模板参数的多态类的模板推导失败
- POCO::PostgreSQL:如何将std::vector支持添加到`Binder::bind`
- 视图中的参数推导失败:take_while
- 链接到自行创建的dll失败
- 带有特殊路径部分的"std::filesystem::weakly_canonical"失败
- GetShortPathName在网络驱动器上使用中文文件夹时失败
- gcc和c++17的过载解析失败
- 为什么使用 P/Invoke 调用 dll 时,某些计算机中的 LoadLibrary 失败?
- 在WSL:configure_file上对config_file的每次调用都失败:配置文件时出现问题
- 使用 GCC 卸载的 OpenMP 卸载失败,并出现"Ptx assembly aborted due to errors"
- 使用cmake从源代码构建MySQL连接器/C++失败(与以前的声明冲突)
- 链接阶段在Ubuntu上失败,但在MacOS上失败
- 从父数组测试用例构造二叉树失败
- auto f = bind(dist<>,gen) 在成员声明C++失败。未被识别为函数
- 编译使用 libcxx 的套接字函数 bind() 的代码失败
- c ++:TCP服务器"bind"功能失败(errno 98),如果我在两次连续应用程序启动之间没有等待足够的时间
- Std::bind在boost::asio::ip::tcp::resolver上失败
- 强制超出作用域boost::bind失败