[英]std::function with unique_ptr argument
給定一個功能
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
也有效
下面的代碼使用gcc 4.8進行編譯。 您會注意到,如果未使用move調用“g”(將左值轉換為右值),則代碼無法編譯。 如前所述,綁定成功,因為只有在調用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;
}
解決方法就是擁有
void MyFunction(std::unique_ptr<int>& arg)
但如果您無法更改功能定義,則無效。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.