首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
社区首页 >问答首页 >Return lambda在常量成员函数中捕获非常量this

Return lambda在常量成员函数中捕获非常量this
EN

Stack Overflow用户
提问于 2021-11-11 17:11:02
回答 1查看 29关注 0票数 0

在一个纯const虚成员函数中,我想返回一个lambda供以后使用。lambda稍后会更改对象,但这在函数外部,并且不会破坏成员函数的cv限定符。我如何才能做到这一点?const_cast是一种可能性吗?

EN

回答 1

Stack Overflow用户

发布于 2021-11-11 17:23:50

您可以在lambda中使用const_castthis转换为可变的。

代码语言:javascript
代码运行次数:0
运行
复制
#include <functional>
#include <iostream>

using std::cout;
using std::function;
using std::ostream;

namespace abstract {
struct Foo {
    virtual ~Foo() = default;
    virtual auto get_remote_control() const -> function<void()> = 0;
};
} // abstract

namespace concrete {
struct Bar : abstract::Foo {
    int state = 0;
    auto get_remote_control() const -> function<void()> override;
};

static auto operator<<(ostream& out, Bar const& bar) -> ostream& {
    return out << bar.state;
};
} // concrete

int main() {
    concrete::Bar bar;
    abstract::Foo const& foo = bar;
    auto remote_control = foo.get_remote_control();
    cout << "Before, Bar{" << bar << "}\n";
    remote_control();
    cout << "After, Bar{" << bar << "}\n";
}

auto concrete::Bar::get_remote_control() const -> function<void()> {
    return [this]{ Bar& mut_self = *const_cast<Bar*>(this); ++mut_self.state; };
}

注意事项有:

  • 栏对象实际上必须是非常数。如果它实际上是const,则后续的++mut_self.state将是未定义的行为(谢谢您的更正)。未定义的行为可能会导致一个很难找出的错误。
  • 封装在function<void()>对象中的返回的lambda会导致一些overhead.
  • The lambda持有指针。如果Bar对象被析构,然后调用lambda,则将通过悬空指针调用它。它也是未定义的behavior.
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69932269

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档