2016-12-16 80 views
0

我寫了結構MyParam,以便它可以使用任意數量的參數進行實例化,在本例中爲intbool。出於封裝原因,我希望MyParams包含自己的promise,以便它可以報告何時完成某件事情。但是當我將這個語句添加到結構中時,它失敗了。儘管如此,作爲一個全球性的公司,它運作良好下面是代碼:當包含一個std :: promise作爲成員時,爲什麼make_unique結構失敗?

#include <tuple> 
#include <memory> 
#include <future> 

//std::promise<bool> donePromise; // OK: if at global level, then make_unique error goes away 

template< typename... ArgsT > 
struct MyParams 
{ 
    MyParams(ArgsT... args) : rvalRefs { std::forward_as_tuple(args...) } {} 

    std::tuple<ArgsT...> rvalRefs; 
    std::promise<bool> donePromise; // causes make_unique to fail when donePromise is a member of MyParams 
}; 

int main() 
{ 
    int num { 33 }; 
    bool tf { false }; 
    MyParams< int, bool > myParams(num, tf); // OK 
    auto myParamsUniquePtr = std::make_unique< MyParams< int, bool > >(myParams); 

    std::future<bool> doneFuture = myParams.donePromise.get_future(); // OK: when donePromise is a global 

    return 0; 
} 
error C2280: 'MyParams<int,bool>::MyParams(const MyParams<int,bool> &)': attempting to reference a deleted function 

什麼我與問候到promise語句作爲成員失蹤?

回答

2

std::promise不可複製構建。

std::make_unique< MyParams< int, bool > >(myParams) 

以上,make_unique試圖複製其構造是形成不良的,由於promise數據成員的存在的MyParams< int, bool >。如果您移動構造,則可以獲得編譯代碼。

std::make_unique< MyParams< int, bool > >(std::move(myParams)) 
相關問題