2017-10-28 97 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

相关问题