2017-10-28 167 views
0

代碼粘貼在下面的一些註釋。我需要看一下std::priority_queue<std::unique_ptr<...>>的頂部,但是如果我調用.top(),則會出現編譯器錯誤:「試圖引用已刪除的函數」。我知道我可以調用pop,但是我需要先根據值來做一些邏輯來確定是否要彈出它。如何在std :: priority_queue <std :: unique_ptr <...>>頂部查看沒有彈出或取得所有權

struct MyStruct { 
    int val = 2; 

    MyStruct(const int val) : val(val) {} 
}; 

void testDeque() { 
    // This block won't compile because of call to q1.top() 
    std::priority_queue<std::unique_ptr<MyStruct>> q1; 
    q1.emplace(std::make_unique<MyStruct>(10)); 
    // How can I "peek" at the value at q1.top() without taking ownership of the unique_ptr? 
    MyStruct* nonOwnershipPtr = DO_SOMETHING_MAGIC(q1.top()); 
    // At this point, the unique_ptr at t1.top() should still be there 
} 
+0

'頂部()'給你參考,並應該讓你做你想做的。您可能在'DO_SOMETHING_MAGIC'中有一個錯誤。 –

+0

@KerrekSB不一定是該函數中的一個錯誤;只需要通過'const&'來取其參數。 –

回答

2

這應該工作:

MyStruct* nonOwnershipPtr = q1.top().get(); 
+0

[Demo](https://wandbox.org/permlink/0DVhotMZekeInB2K) –

+0

呃。我知道我嘗試過。但是由於錯誤出現在「xmemory0」中,而不是告訴我我的代碼在哪裏出錯,所以我可能在其他地方發生了錯誤。謝謝! – mentics

相關問題