c++ - 带有 unique_ptr 参数的 std::function

标签 c++ c++11 unique-ptr std-function stdbind

给定一个函数

void MyFunction(std::unique_ptr<int> arg);

不可能(MSVC 2012)创建像这样的仿函数

std::function<void(std::unique_ptr<int>)> f = std::bind(&MyFunction, std::placeholders::_1);

问题不在于绑定(bind) - 使用 auto f = std::bind(...) 可以。此外,使用 shared_ptr 也有效

  • 为什么不允许使用 unique_ptr?
  • 这是 MSVC 问题还是一般的 C++11 限制?
  • 是否有不更改函数定义的解决方法?

最佳答案

下面的代码使用 gcc 4.8 编译良好。你会注意到 如果没有用 move 调用“g”(将左值转换为右值), 代码无法编译。如前所述,绑定(bind)成功是因为 失败仅在调用 operator()( ... ) 时发生,因为 unique_ptr 不可复制的事实。调用“f”是允许的,因为 shared_ptr 有一个复制构造函数。

#include <functional>
#include <memory>


void foo1( std::shared_ptr<int> ){}
void foo2( std::unique_ptr<int> ){}

int main() 
{
    using namespace std::placeholders;

    std::function<void(std::shared_ptr<int>)> f = std::bind( foo1, _1 );
    std::function<void(std::unique_ptr<int>)> g = std::bind( foo2, _1 );

    std::unique_ptr<int> i( new int(5) );
    g( move( i ) ); //Requires the move

    std::shared_ptr<int> j( new int(5) );
    f( j ); //Works fine without the move
    return 0;
}

关于c++ - 带有 unique_ptr 参数的 std::function,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17141185/

相关文章:

c++ - 在单元测试中初始化 unique_ptr

c++ - 如何将数据传递给引用包装器

c++ - gcc 版本之间的舍入差异

c++ - 如何检测整个周期的C++随机引擎已经被消耗

c++ - 为什么 std::distance 不适用于 const 和非 const 迭代器的混合?

c++ - 有人可以解释这个 unique_ptr 代码发生了什么吗?

c++ - 我的变量不会有任何值(value)

c++ - QDataStream 和 quint16 序列化怪异

C++11 unique_ptr 数组和构造函数参数

C++17:unique_ptr<char[]> 和shared_ptr<char[]> 之间指针存储的差异