【问题标题】:std::function with unique_ptr argument带有 unique_ptr 参数的 std::function
【发布时间】:2013-06-17 05:57:59
【问题描述】:

给定一个类似的函数

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

不可能(MSVC 2012)创建类似的仿函数

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

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

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

【问题讨论】:

  • 请注意,这与已解决的std::bind(&amp;MyFunction, std::unique_ptr()) 不同,例如stackoverflow.com/questions/9955714/…
  • “不可能创建仿函数”是什么意思?你的代码完美地为我编译。 Example.
  • 问题已更新编译器信息,您使用 gcc 吗?
  • g++ 和 clang++。你能发布一个编译器错误吗?
  • 一百万行模板错误,最嵌套的是:VC\include\functional(1152): error C2248: 'std::unique_ptr&lt;_Ty&gt;::unique_ptr' : cannot access private member declared in class 'std::unique_ptr&lt;_Ty&gt; - 所以似乎正在某个地方尝试复制,我不会认为在这种情况下这是必要的。如果你让它在 g++ 中工作,这似乎是特定于 MS 的,考虑到对 C++11 的支持程度不同,这并不奇怪

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


【解决方案1】:

下面的代码使用 gcc 4.8 编译得很好。你会注意到 如果“g”没有被 move 调用(将左值转换为右值), 代码无法编译。如前所述,绑定成功是因为 失败仅在调用 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;
}

【讨论】:

  • 这似乎表明这是一个 MSVC 问题 - 很高兴知道代码是合法的。
【解决方案2】:

解决方法是让

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

但是如果你不能改变函数定义,那是行不通的。

【讨论】:

    猜你喜欢
    • 2013-12-14
    • 2016-03-21
    • 2019-12-13
    • 1970-01-01
    • 1970-01-01
    • 2022-01-05
    • 1970-01-01
    • 2017-01-04
    • 1970-01-01
    相关资源
    最近更新 更多