c++ - std::bind 是否有可变版本?

标签 c++ c++11 lambda immutability

我正在尝试在std::unique_ptrstd::bind一个std::move。生成的函数对象似乎是不可变的,因此在调用仿函数时不可能执行移动。

我怀疑这与 lambda 默认情况下不可变的原因相同 - 调用它们每次都应该执行相同的操作。然而,在某些情况下它们需要可变,这就是我们使用 mutable 关键字的原因。

void foo(std::unique_ptr<int>&& ptr)
{
    cout << *ptr << endl;
}

int main()
{
    std::unique_ptr<int> ptr = std::make_unique<int>(123);
    std::bind(foo, std::move(ptr))();             // Doesn't compile
    [&ptr]() { foo(std::move(ptr)); }();          // Equivalent, doesn't compile
    [&ptr]() mutable { foo(std::move(ptr)); }();  // Compiles
    return 0;
}

除了使用bind,我还可以将函数调用包装在可变的 lambda 中。不过,至少对我个人来说,在这种情况下,bind 看起来更加干净和简单。

我知道调用可变 lambda 两次会导致未定义的行为,因为我将从已经移出的指针再次移动。但就我而言,我知道仿函数只会被调用一次。

有没有办法使用std::bind来做到这一点?是否存在某种bind_mutable?如果没有,我该怎么自己写呢?

最佳答案

However at least to me personally bind looks much cleaner and simpler in this case.

不要在 C++11 中使用 std::bind。请改用 lambda。 std::bind 有几个问题 excellently explained in this talk by Stephan T. Lavavej “functional: What's New, And Proper Usage" .

screenshot from talk

在这种情况下,它可能看起来更简单、更干净,但不建议这样做。

正在写...

[&ptr]{ foo(std::move(ptr)); }(); 

...是解决这个问题的正确方法。

关于c++ - std::bind 是否有可变版本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46971436/

相关文章:

c++ - 模板参数推导与 QT lambda 不匹配

.net - TeeChart VCL 与 .NET

c++ - 我可以使用 nullptr 作为 Linux 系统调用参数吗?

c++ - 有没有一种可移植的方法来知道 uintptr_t 是否在 stdint.h 中定义?

c++ - 在模板类中编写的 lambda 函数不支持 restrict(...) 吗?

c++ - 我什么时候应该 std::forward 一个函数调用?

c++ - GetQueuedCompletionStatus 在 UDP 套接字上无限期阻塞

c++ - 蓝牙与电脑交互

c++ - 是否可以在 C++ 中使用匿名类?

c++ - 表达式不是积分常量 clang libc++ threading