代碼粘貼在下面的一些註釋。我需要看一下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
}
'頂部()'給你參考,並應該讓你做你想做的。您可能在'DO_SOMETHING_MAGIC'中有一個錯誤。 –
@KerrekSB不一定是該函數中的一個錯誤;只需要通過'const&'來取其參數。 –