c++ - 在 boost scope exit 中调用对象函数

标签 c++ boost scope

我有以下代码: 如何在范围退出中调用成员函数。

class A
{
public:
    void foo();
    void bar();
};

void A::foo() 
{
    BOOST_SCOPE_EXIT(void)
    {
        bar(); // Does not compile
    }
    BOOST_SCOPE_EXIT_END
}

void A::bar() {}

void foo4()
{
    A a;    
    a.foo();
} 

错误信息

boost_scope_exit.cpp: In static member function ‘static void  
A::foo()::boost_se_guard_t_71::boost_se_body()’:
boost_scope_exit.cpp:73:13: error: cannot call member function ‘void          
A::bar()’ without object
     bar(); // Does not compile
         ^

如何从作用域导出调用成员函数。

在boost文档中找到答案:

Boost docs

只需搜索“捕获对象”

最佳答案

如果您将 bar 设为静态(并调用 A::bar()),您的代码将正常工作。
如果那不是一个选项,那么您似乎需要捕获 this 指针 使用特殊符号 this_(注意结尾的下划线)。

BOOST_SCOPE_EXIT(this_)
{
    this_->bar();  // note trailing underscore on this_
}
BOOST_SCOPE_EXIT_END

关于c++ - 在 boost scope exit 中调用对象函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37174252/

相关文章:

c++ - 如何显式调用CRT启动函数

c++ - 如何通过鼠标单击获取相对的 x 和 y 位置

c++ - 如何使用 boost 库反序列化和获取成员值

boost - 如何将 OGRLineString 注册为 boost 线串?

c - 从 C 中的函数返回数组

c++ - 在 VS2012 中使用 CMAKE 将启用增量链接设置为 NO

c++ - Visual C++ 9.0 (2008) 静态库 + Boost 库 = 大型 .lib 文件

c++ - boost asio async_read 中的随机 EOF

java - 从finally block 访问时try block 内的变量范围?

dependency-injection - .Net 核心 : Custom scope for "Scoped" Dependency injection w. 输出。 Controller